<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Barış Dede on Medium]]></title>
        <description><![CDATA[Stories by Barış Dede on Medium]]></description>
        <link>https://medium.com/@baris5d?source=rss-69f3241c7a7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I4lyrhZzpeyPgwZxGAU9zQ.jpeg</url>
            <title>Stories by Barış Dede on Medium</title>
            <link>https://medium.com/@baris5d?source=rss-69f3241c7a7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baris5d/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Full-Stack With Django and React — React]]></title>
            <link>https://medium.com/swlh/full-stack-with-django-and-react-react-afae36017852?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/afae36017852</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:18:56 GMT</pubDate>
            <atom:updated>2020-08-19T19:31:45.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Full-Stack With Django and React — React</h3><p>This article is a continuation of Django and React Full Stack — Django. If you have not read that part or your backend environment is not ready, you can find the article I developed using Django — I shared my notes while developing — <a href="https://medium.com/@baris5d/full-stack-with-django-and-react-django-4dcd87d57356"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ikFbXGafVdsDDCJAzrvfBg@2x.png" /></figure><p>I know it’s a very comprehensive title so I’ll keep it as simple as possible.</p><p>In this article, we will make a book application from installation to the final product using Django and React. I hope to make a nice and simple introduction-development-product series for a CRUD (Create, Read, Update, Delete) application. I want to share the notes I took and the steps I followed while making an app without getting overwhelmed by a lot of information from both sides (back end and front end).</p><p>I will try not to dwell on the questions such as what and why, but to explain it purposefully. For every command I use, I will cite since there may be people who do not know, in this way you can quickly get an idea from their documentation pages and return to the article.</p><p><a href="https://www.djangoproject.com/">Django </a>is a Python-based free and open-source web library based on the model-template-view architecture.</p><p><a href="https://reactjs.org/">React </a>is a JavaScript library that allows you to create user interfaces for your web projects on a component basis.</p><h3>Getting started #1</h3><p>We established our backend structure with Django, we used our data with HTML. Now it’s time to heat things up a bit. If you still haven’t read that article, you can read it here.<br>We can start by installing our React application in our project.</p><h3>Installation</h3><p>Inside of our project, run npx create-react-app frontend on the command line. The reason I create a project called Frontend is that I don’t want the files to interfere and appear more understandable. I want the node files and Django files in separate folders so that they are easy to access and edit.</p><p>After installation is done, run cd frontend &amp; npm start commands. While running the project browser will be opened automatically and you’ll see your first react app. If it runs on another port you can see which port react using is on the terminal screen.</p><h4>How much should I know?</h4><p>If you use React the first time or you’ve never written JavaScript you may have some struggle. If we consider it as JavaScript, not just React: it can be a bit annoying to adapt to an asynchronous language. JavaScript is not a completely top-down language. Do not be surprised if the code you write at the bottom works before you write at the top. It is beautifully described as titles at <a href="https://javascript.info/">https://javascript.info/</a>. At least, getting enough information to understand what you read later in the article will make your job easier in the continuation of the article.</p><h4>Functional Components</h4><p>To create our interface we’ll use functional components. The reason we prefer functional components is that convenience about readability, renewability, and testing.</p><p>I don’t want to dig the difference between class and functional components. Focusing on the pros and cons of them will probably deflect us from our main goal of this article. If you want to focus on these, you may follow the link below.</p><p>Function and class components: <a href="https://tr.reactjs.org/docs/components-and-props.html">h</a>ttps://tr.reactjs.org/docs/components-and-props.html</p><p>The idea of developing based on functional components will be saved us from excess codes and disorganization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2845becd237ec18edf55f69abd13355/href">https://medium.com/media/d2845becd237ec18edf55f69abd13355/href</a></iframe><p>The above code is the first functional component that comes with the installation of react. It returns a DOM element which includes header, image and a text. It looks clean and basic, right? Let’s start with writing code that lists our books.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e55c7f91ca26dbfc34d2a1700dcdea4/href">https://medium.com/media/8e55c7f91ca26dbfc34d2a1700dcdea4/href</a></iframe><p>With basic HTML knowledge we prepared a template for our books list. The only difference between HTML and JSX is that we used className instead of class — for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*RcXfQNkP4bKpTeaGNGV4kQ.png" /></figure><h4>Hooks — useEffect ve useState</h4><p>Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.(<a href="https://reactjs.org/docs/hooks-intro.html#no-breaking-changes">https://reactjs.org/docs/hooks-intro.html#no-breaking-changes</a>)</p><p>In React lifecycle there’s some methods such as componentDidMount , componentDidUpdate andcomponentWillUnmount . With hooks we use useEffectfor all of them .</p><p>Let’s import useState and useEffect and define our first state inside of function.</p><pre>import {useState, useEffect } from &#39;React&#39;</pre><pre>function App(){...<br>const [books, setBooks] = useState([])<br>...<br>}</pre><p>I defined a state named books and initialized it with an empty array. This process was as follows in the class components:</p><pre>class Test extends React.Component{<br>  constructor(props){<br>    super(props)<br>    this.state = {<br>      books : []<br>    }<br>  }<br>}</pre><p>Now we see first benefit of functional components. Let’s try to fill our state and use it with useEffect.</p><pre>useEffect (() =&gt; {<br>    setBooks([<br>         {<br>           &quot;name&quot;:&quot;Otostopçunun Galaksi Rehberi&quot;, <br>           &quot;author&quot;:    &quot;Douglas Adams&quot;, <br>           &quot;description&quot;: &quot;Lorem ipsum&quot;<br>         },<br>         {<br>           &quot;name&quot;:&quot;Hikayeler&quot;, <br>           &quot;author&quot;:    &quot;Edgar Allan Poe&quot;, <br>           &quot;description&quot;: &quot;Lorem ipsum sit door amet&quot;<br>         }<br>      ])<br>},[])</pre><p>We placed two objects in our books state. Now, let me print them with JSX using Array.prototype.map</p><pre>books.map((<em>book</em>,<em>index</em>) =&gt; {<br>   return (<br>     &lt;div <em>className</em>=&quot;book-item&quot;&gt;<br>       &lt;h2&gt;{<em>book</em>.name}&lt;/h2&gt;<br>       &lt;p&gt;{<em>book</em>.author}&lt;/p&gt;<br>       &lt;p&gt;{<em>book</em>.description}&lt;/p&gt;<br>    &lt;/div&gt;<br>   )}<br>)}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Zxomqfu3w5l3MbEDfwYWDw.png" /></figure><p>When we run our code, we can now see the data. However, we will get this data from the API we prepared with django. On the Django side, we received our data with XMLHttpRequst operation with pure javascript. We can run the same code again, but we will go one step further and this time we will use the Fetch API, which allows us to retrieve data from a different address.</p><h4>Fetch API</h4><p>We will get our data via the REST API that I prepared with Django. If you have not read this series from the beginning and are using a different backend infrastructure, this process will be the same on front-end side.</p><p>Let’s send a request to get our data from API and store them.</p><pre>useEffect (() =&gt; {<br>   async function fetchBooks() {<br>     const res = await fetch(&quot;http://127.0.0.1:8000/books/&quot;);<br>     res.json()<br>    .then(<em>res</em> =&gt; setBooks(<em>res.response</em>))<br>    .catch(<em>err</em> =&gt; setErrors(<em>err</em>));<br>   }<br>   fetchBooks();<br>},[])</pre><p>You may find more information about async functions from this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">link</a>. To explain this with an example:</p><pre>getBooks = () =&gt; {<br>    console.log(&#39;first book&#39;);    <br>    setTimeout(() =&gt; {<br>        console.log(&#39;second book&#39;);    <br>},3000);    <br>console.log(&#39;third book&#39;);}</pre><pre>getBooks ();</pre><p>JavaScript has a sync and single-thread structure. After printing first bookin the above code, it will print third bookand then wait for 3 seconds and display the second bookoutput. The reason we use asyn function is that we want it to wait for that 3 seconds.</p><p>Now returning to the react side (I assume Django and React are working) when we open the browser, we will see an error on the console like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*1j17_KBVzWenfiWS6OIhrw.png" /></figure><p><strong>Cross-Origin Resource Sharing</strong> (<a href="https://developer.mozilla.org/en-US/docs/Glossary/CORS">CORS</a>) is a mechanism that uses additional <a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP">HTTP</a> headers to tell browsers to give a web application running at one <a href="https://developer.mozilla.org/en-US/docs/Glossary/origin">origin</a>, access to selected resources from a different origin.</p><p>In order to our API resource to grant this access, we need to configure Django.</p><p>Runningpipenv install django-cors-headers code on back-end side we install django-cors-headers app. You may see more details of its installation on the <a href="https://pypi.org/project/django-cors-headers/">documentation </a>page.</p><p>After installation is done configure settings.py file as follows:</p><p>Add corsheadersinto INSTALLED_APPS and &#39;cors.headers.middelware.Corsmiddleware into MIDDLEWARE .</p><p>Now we should determine which addresses can be accessed. We can do this in two ways: allowing all addresses or determine particular addresses.</p><pre>CORS_ORIGIN_WHITELIST = [<br>    &quot;https://example.com&quot;,<br>    &quot;https://sub.example.com&quot;,<br>    &quot;http://localhost:8080&quot;,<br>    &quot;http://127.0.0.1:9000&quot;<br>]</pre><p>You may also use a regex pattern. After saving the file, now we can see the data on the browser.</p><p>Since we run it in a way, we can do a little more simplification. Let’s not forget that we work component-based. We printed our books on the screen in a direct loop. Let’s take this data as a separate component.</p><p>We create a new function called Book and set its return value as the elements we list in our books.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a1da45d61f70209f6ca5176ed9190c8/href">https://medium.com/media/6a1da45d61f70209f6ca5176ed9190c8/href</a></iframe><p>We received the prop named book from the incoming props and we can now print it on the screen. When we add &lt;Book book={item} key={index} /&gt;code between our map code in the app, will see the same list again. (I changed the name of the book variable to item to avoid confusion)</p><p>For the repetitive values, React asked us to send a selector, so we sent our index value into the key.</p><p>Now, let’s move book creation page to React side. We create a new component and place our form elements in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3042aa5424baad34178036c8c7f8cf0f/href">https://medium.com/media/3042aa5424baad34178036c8c7f8cf0f/href</a></iframe><h4>Axios</h4><p>We created our form in a basic way. We will use Axios to send our data to API within POST method. In doing so, we will benefit from React Hooks. We will keep our input values in the state, and when we press the save button, we will catch the submission and perform the operations we want with axios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef8ab38442892b7fb97fd44a165b0b38/href">https://medium.com/media/ef8ab38442892b7fb97fd44a165b0b38/href</a></iframe><h4>CSRF Token</h4><p>When we send our form we’ll see it will not be saved and return 400 status code(Bad request). The first reason of it is that back-end side await a csrf token from us. In the <a href="https://docs.djangoproject.com/en/3.0/ref/csrf/">documentation </a>page, you can see how you can send csrf token. We will use same getCookie function which exists in documentation page. Default cookie name is csrftoken , if you desire you may change it from settings.py page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4996567b97193b6c8ad3b9b8c4adcbe8/href">https://medium.com/media/4996567b97193b6c8ad3b9b8c4adcbe8/href</a></iframe><p>Now, we can see the csrftoken information on the network tab of the browser. But, what!? It still returns 400 status code. When we check our serialize code on back-end side we realize that the data we are trying to save is empty. BooksSerializer(data=request.POST or None)</p><p>The output of print(request.POST) is &lt;QueryDict: []&gt; . Now the value we need is request.data instead of requst.POST . After changing the data we try to serialize with request.data, we can save it.</p><p>Learn more about CSRF Token parameters you may visit <a href="https://docs.djangoproject.com/en/3.0/ref/csrf/">this </a>page.</p><h4>React Routing</h4><p>Last but not least, we want it to be separated pages with special URLs. We can do these things in a single page but I want it to touch router structure too.</p><p>Paste it onto the command line: npm install react-router-dom</p><p>I’ve done all components in a single page, you can import seperated components onto different pages and folders using import { ComponentName } from ‘path/file and use them as &lt;ComponentName /&gt;</p><p>App component lists our books and there is a form also. Let’s separate them and set a router. Keep App component which lists our books. Remove export default App code from bottom of the file to change our default function as router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3011e5c5068814c109ecde882fb86be/href">https://medium.com/media/b3011e5c5068814c109ecde882fb86be/href</a></iframe><p>Like me, do not forget to import the libraries you use.</p><pre>import {<br>  <em>BrowserRouter</em> as Router,<br>  Switch,<br>  Route,<br>  Link<br>} from &quot;react-router-dom&quot;;</pre><p>Now, to make Landing component index page, change the default component as Landing in index.js file.</p><p>When we refresh the page, we will see the menu links we created in the form of a list at the top of the page. Since we are in the main directory, the &lt;App /&gt; component will be called and our books will be listed.</p><p>Let’s write the code to show singular book with an id in a page. It’s almost same with our full list code. The only difference is that if it doesn’t exist in our database it will return an error message. We already configured our API to return a 404 page if there’s no data. We’ll control it with a status message such as ok/error. And let’s write our code as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a716d45299352a495c82bd7b6e292d2/href">https://medium.com/media/9a716d45299352a495c82bd7b6e292d2/href</a></iframe><p>Now, when we enter localhost:3000/books/1 address, if there’s a data with 1 id in the database, it will print it. If an error occurs or our status code is not 200, it will print the message “Something went wrong” on the screen.</p><p>In the code we list our books, add a hyperlink to our titles to be able to go into the details page.</p><p>Change book listing code as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2d684e0302e2544c32ed0abe10b2f8a/href">https://medium.com/media/a2d684e0302e2544c32ed0abe10b2f8a/href</a></iframe><p>Now we can click the titles and go into their detail pages.</p><p>After everything is completed, we can build our optimized react application via npm run build and see them in a folder named build.</p><p>So far, we didn’t do anything about styling. I’ll add CSS codes later to the repository but our main goal is to try to understand the main structure. We could deal with CSS later on. You can see the source codes I use in this article on <a href="https://github.com/baris5d/DjangoReact">Github</a>, and contribute if you wish.</p><p>You can contact me if you have any questions or about anything you need via my <a href="https://twitter.com/baris5d">Twitter </a>account.</p><p>Happy codding! :)</p><p>Github, Twitter, Instagram : @baris5d</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afae36017852" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/full-stack-with-django-and-react-react-afae36017852">Full-Stack With Django and React — React</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack With Django and React — Django]]></title>
            <link>https://medium.com/swlh/full-stack-with-django-and-react-django-4dcd87d57356?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dcd87d57356</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:18:42 GMT</pubDate>
            <atom:updated>2023-04-13T17:21:15.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>Full-Stack With Django and React — Django</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hiAOg-RRpXjBFAA06SDdpA@2x.png" /></figure><p>I know it’s a very comprehensive title so I’ll keep it as simple as possible.</p><p>In this article, we will build a book application from installation to the final product using Django and React. I hope to make a nice and simple introduction-development-product series for a CRUD (Create, Read, Update, Delete) application. I want to share the notes I took and the steps I followed while making an app without getting overwhelmed by a lot of information from both sides (back end and front end).</p><p>I will try not to dwell on the questions such as what and why, but to explain it purposefully. For every command I use, I will cite since there may be people who do not know, in this way you can quickly get an idea from their documentation pages and return to the article.</p><p><a href="https://www.djangoproject.com/">Django </a>is a Python-based free and open-source web library based on the model-template-view architecture.</p><p><a href="https://reactjs.org/">React </a>is a JavaScript library that allows you to create user interfaces for your web projects on a component basis.</p><h3>Getting started #1</h3><p>Here’s what you need to have installed on your computer before keeping to read the article:</p><pre><a href="https://www.python.org/">Python3</a></pre><pre><a href="https://pypi.org/project/pip/">Pip</a></pre><pre><a href="https://nodejs.org/en/">NodeJS</a></pre><p>While I’m writing this article I use the following versions : Python 3.6~, pip 20.1.1, NodeJS 12.18.2 . If the scripts I use not work or give an error on different versions, please do not hesitate to ask me.</p><p>Let’s start by setting up a working environment. I created a folder named as DjangoReact. First step is installing pipenv. Pipenv is a tool that brings packaging processes(bundler, npm, yarn, composer, etc.) to python world. It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your Pipfile as you install/uninstall packages.</p><p>Paste the below code to the command line after going into the workspace:</p><pre>python3.6 -m pip install pipenv --upgrade</pre><p>Afterward, via the below code we’ll install django 3.0.8(latest version) to our virtualenv via the below code:</p><pre>pipenv install --python 3.6 django==3.0.8</pre><p>After installation is done, our folder tree must be as follows:</p><pre>DjangoReact<br>├── Pipfile<br>└── Pipfile.lock</pre><p>To be activated virtualenv run pipenv shell code on the command line.</p><p>Now, we can start to create our first Django project. You may see the parameters you could use by typing django-adminon the command line. For now, we just interested in a parameter called startproject. Since we want to install to the folder we are in (we have already created a folder at the beginning of the article), we are creating a project called DjangoReact to the folder we are in.</p><pre>django-admin startproject DjangoReact .</pre><p>Here is the final folder tree:</p><pre>DjangoReact/<br>    manage.py<br>    DjangoReact/<br>        __init__.py<br>        settings.py<br>        urls.py<br>        asgi.py<br>        wsgi.py</pre><p>I want to take a note here that projects and applications are completely different kinds of things. The application is a web application that serves a specific purpose — blog, todolist, database records, etc. while the project is a collection of applications and configurations within a website. The project can contain more than one application.</p><p>To check, we run our server and check that it is working properly. When we run the python manage.py runserver code, the output in the terminal should be as follows.</p><pre>(DjangoReact) $~ python manage.py runserver</pre><pre>Watching for file changes with StatReloader<br>Performing system checks…<br>System check identified no issues (0 silenced).</pre><pre>You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.<br>Run ‘python manage.py migrate’ to apply them.</pre><pre>July 17, 2020–14:22:01<br>Django version 3.0.8, using settings ‘backend.settings’<br>Starting development server at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a><br>Quit the server with CONTROL-C.</pre><p>When we enter our localhost, the screen below appears. Yes! It works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpdJoLREx2aIWdaiQ-M9dQ.png" /><figcaption>127.0.0.1</figcaption></figure><p>One last little touch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4s_2PvMFQKSGjfLWBjXWw.png" /></figure><p>Yes! Now we can add Django to our skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*qKHwBXKxuBUIQ4DH9NCRyQ.gif" /></figure><h3>Model, View, Routing…URLs #2</h3><p>Now, it’s time to create our first application. Our to-do list is as follows:</p><pre>1. Books</pre><pre>-&gt; Creating</pre><pre>-&gt; Name?</pre><pre>-&gt; Author?</pre><pre>-&gt; Description?</pre><pre>-&gt; Image?</pre><pre>-&gt; Search</pre><pre>-&gt; Delete</pre><pre>-&gt; Update</pre><pre>2. Feed</pre><pre>-&gt; List of all books</pre><p>We come into DjangoReact folder and create an application with ./manage.py startapp books command. After running the command, it will create a folder named ‘books’ inside our folder and install it. The final version of our folder is as follows:</p><pre>DjangoReact/<br>├── books<br>│   ├── admin.py<br>│   ├── apps.py<br>│   ├── __init__.py<br>│   ├── migrations<br>│   │   └── __init__.py<br>│   ├── models.py<br>│   ├── tests.py<br>│   └── views.py<br>├── db.sqlite3<br>├── DjangoReact<br>│   ├── asgi.py<br>│   ├── __init__.py<br>│   ├── __pycache__<br>│   │   ├── __init__.cpython-36.pyc<br>│   │   ├── settings.cpython-36.pyc<br>│   │   ├── urls.cpython-36.pyc<br>│   │   └── wsgi.cpython-36.pyc<br>│   ├── settings.py<br>│   ├── urls.py<br>│   └── wsgi.py<br>├── manage.py<br>├── Pipfile<br>├── Pipfile.lock<br>└── todo.md</pre><h4>Model</h4><p>We should configure our model.py file in books application as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157472e9eeb70810d68f1f0a3bd7d3e1/href">https://medium.com/media/157472e9eeb70810d68f1f0a3bd7d3e1/href</a></iframe><p>With models.TextField(), we define the name, author and description fields. blank = False and null = False fields need to be filled, even if others are empty. Since the id field will increase automatically and will be used as a selector, we have defined it as AutoField and primary key. In order to get our cover images, we determined the file path using FileField and said that this field can be left blank.</p><h4>Migrate</h4><p>In order to recognize our application when the project is running, we need to find the INSTALLED_APPS in the settings.py file under our project folder, add and save our model name &#39;books&#39; . After doing this, we run python manage.py makemigrations command to write the changes we made in our model to the database scheme. After completion, we apply the changes we made with python manage.py migrate command.</p><pre>$~ python manage.py migrate</pre><pre><strong>Operations to perform:</strong><br>  Apply all migrations: admin, auth, books, contenttypes, sessions<br><strong>Running migrations:</strong><br>  Applying contenttypes.0001_initial... OK<br>  Applying auth.0001_initial... OK<br>  Applying admin.0001_initial... OK<br>  Applying admin.0002_logentry_remove_auto_add... OK<br>  Applying admin.0003_logentry_add_action_flag_choices... OK<br>  Applying contenttypes.0002_remove_content_type_name... OK<br>  Applying auth.0002_alter_permission_name_max_length... OK<br>  Applying auth.0003_alter_user_email_max_length... OK<br>  Applying auth.0004_alter_user_username_opts... OK<br>  Applying auth.0005_alter_user_last_login_null... OK<br>  Applying auth.0006_require_contenttypes_0002... OK<br>  Applying auth.0007_alter_validators_add_error_messages... OK<br>  Applying auth.0008_alter_user_username_max_length... OK<br>  Applying auth.0009_alter_user_last_name_max_length... OK<br>  Applying auth.0010_alter_group_name_max_length... OK<br>  Applying auth.0011_update_proxy_permissions... OK<br>  Applying books.0001_initial... OK<br>  Applying sessions.0001_initial... OK</pre><p>Let’s test our model on the terminal and see how it works. Run the shell writing ./manage.py shell and apply the codes below.</p><pre>&gt;&gt;&gt; from books.models import Books<br>&gt;&gt;&gt; obj = Books()<br>&gt;&gt;&gt; obj.name = &quot;Otostopçunun Galaksi Rehberi&quot;<br>&gt;&gt;&gt; obj.author = &quot;Douglas Adams&quot;<br>&gt;&gt;&gt; obj.description = &quot;Uzaylı gören masum köylü&quot; # null veya blank olabilir dediğimiz için bu kısmı boş geçebilirsiniz.<br>&gt;&gt;&gt; obj.save()<br>&gt;&gt;&gt; exit()</pre><p>If you don’t get any error messages re-enter the shell and run the below codes to see either your records have been saved or not.</p><pre>&gt;&gt;&gt; from books.models import Books<br>&gt;&gt;&gt; firstBook = Books.objects.get(id=1)<br>&gt;&gt;&gt; firstBook.name<br>&#39;Otostopçunun Galaksi Rehberi&#39;<br>&gt;&gt;&gt; exit()</pre><h4>View</h4><p>Let’s mess with the view side a bit. Open views.py file under our ‘books’ folder and print “Hello World” message to perform a ritual.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e75b8b33ecefea5e0a4124dd11d9a33d/href">https://medium.com/media/e75b8b33ecefea5e0a4124dd11d9a33d/href</a></iframe><p>And we define the paths to the urls.py file as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f3814e99e0a1373aac8a7a735ce181/href">https://medium.com/media/30f3814e99e0a1373aac8a7a735ce181/href</a></iframe><p>I know it’s hard to guess. Who knows what will come across when we enter 127.0.0.1. Yes. It was a joke, a bad one. And now we see “Hello world!” message on our screen again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*oas76xwNnP_JALfHYKDlSQ.gif" /></figure><h4>Dynamic URLs</h4><p>Let’s create one more function to the view file and print parameters coming with URL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f810f3ee0799a8ae275ea7ec4af020/href">https://medium.com/media/d3f810f3ee0799a8ae275ea7ec4af020/href</a></iframe><p>Of course, there’s no router to run this code. So, add path(&#39;books/&lt;int:book_id&gt;&#39;, book_detail_view) into urlpatterns. And do not forget to importbook_detail_view from book.view</p><p>Now, we can see Hey 1 message when we enter http://127.0.0.1:8000/books/1 address. We used url parameter as a string now. Let’s try to use it to bring book information from our database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e220186cafb66752a06b2e113f0017c/href">https://medium.com/media/6e220186cafb66752a06b2e113f0017c/href</a></iframe><p>It’s easy, isn’t it? Now, when we visit <a href="http://127.0.0.1:8000/books/1">http://127.0.0.1:8000/books/1</a> address on browser, we’ll see the name and author of a book which its id is 1 in database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*FMKDVMRA5zdHrg8yCCLKUw.png" /></figure><p>If we enter an id that doesn’t exist in our database, it will show up an error that there’s no data matched with that id. Let’s catch that error up and return a 404 page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56086be7e08ed4af682e050f5d1c1e26/href">https://medium.com/media/56086be7e08ed4af682e050f5d1c1e26/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*MpiPax6jRj-OLygpMd_ZWw.png" /><figcaption>Default 404 page</figcaption></figure><p>As I said before, it should be a CRUD application so let’s create a form for the book creation part. Create a file named /templates/components/form.htmland create one more file named form.py under our application folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cfe20b4812bd82dcfb5a6de7aa01e96/href">https://medium.com/media/7cfe20b4812bd82dcfb5a6de7aa01e96/href</a></iframe><p>We wrote the above code into theform.py file. When we started to our project and created a model, we defined name, author, and description fields as TextField. In the model we created by calling Django’s ‘forms’ class, we want it to create a form based on the data we want. I wanted to give an example of how we can control the data by limiting the book description. I just wanted to take advantage of Django’s benefits.</p><p>Now, we can use our form in views. Create a function named book_create_view , add it onto urls.py in order to run it when create-book action comes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c370e01deacc7db4e3cff48739523ec3/href">https://medium.com/media/c370e01deacc7db4e3cff48739523ec3/href</a></iframe><p>On the code above, we imported BooksForm from form.py file. While creating a model, we determined which fields should be filled or not. Accordingly, we obtain control from the form class of Django, if there is no data entry other than the expected data, we save the incoming form.</p><p>Let’s see our form template on the interface. form.html file as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc5111acbe7160bd33fea3fa3bb3dcc/href">https://medium.com/media/cfc5111acbe7160bd33fea3fa3bb3dcc/href</a></iframe><p>form.as_p means, wrap all elements between &lt;p&gt; tags. Cross-site request forgery (CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. To block these kind of attacks, it creates a token and checks it on back-end. This is an digressive of our subject but useful information.</p><p>I did not want to make an explanation for the deletion and updating process, in order to avoid the word crowd. To delete a data, you can use Books.objects.filter(id=book_id).delete() and here is the update method:</p><pre>book = Books.objects.get(id=1)<br>book.name = &quot;Yeni isim&quot;<br>book.save()</pre><h3>Templates, REST API, Djangorestframework ve Tests #3</h3><p>Now, we will send the data we have in an HTML Template file and print it on the screen more regularly.</p><h4>Template</h4><p>First of all, we prepare the template folder. We create a folder named templates in the main directory. In order to determine the template path, we find the TEMPLATESarray in our settings.py file and edit the ‘DIRS’ into [os.path.join(BASE_DIR, &quot;templates&quot;)] . Now we have specified our template path. We create an HTML file named /pages/home.html in our templates folder and you can write anything indicating that file is there. I wrote “Hello World from home.html file”. Next, we configure the home_view function in the views section, which we define on the home page, not directly to the screen, but to call our HTML file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f987468ee628d1ec8f4817f6ff64d9a/href">https://medium.com/media/4f987468ee628d1ec8f4817f6ff64d9a/href</a></iframe><p>To run away from repeated-code let’s create a file named base.html and fill it with the codes we’ll use in all pages such as meta tags, titles, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac0cf1af8381efc37e1f53185c20516/href">https://medium.com/media/bac0cf1af8381efc37e1f53185c20516/href</a></iframe><p>If you have ever used a template engine such as twig and blade, this idea won’t sound strange to you. If you have never used it, you may take a look at the documentation pages and see the basic usage and come back. Basically, the template engines allow us to compile data that comes from the backend in dynamic pages, which we break into pieces — menu, header, meta tags, sidebar, etc. — allows us to run our files according to our needs. I continue without distracting the subject.</p><p>Let’s use our base.html file into home.html as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a11e133ef7f2c79d5a310a72fa08b0/href">https://medium.com/media/25a11e133ef7f2c79d5a310a72fa08b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*tGvDzsiKrMI0iQh_qoncQQ.png" /></figure><p>As you can see above, when we enter the main page, it now calls our home.html page. When the page is compiled, as I mentioned above, we integrate it into base.html and get an output like this.</p><h4>REST API — DjangoRestFramework</h4><p>We ran our template and dug a bit. Now it’s better to return our data as json since we use it on front-end. We made our return value as HttpResponse in book_detail_view and home_view. In home_view, we rendered our page over HTML, and in the book_detail_view section, we directly printed it on the screen. We call the JsonResponse class from django.http. We will print our data in a slightly more useful way, rather than directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c50bf0036095c816f64065d457d34ad7/href">https://medium.com/media/c50bf0036095c816f64065d457d34ad7/href</a></iframe><p>In the code above, if searched data exist it returns data object filled with our results. if it’s not it returns an error message. Instead of returning the Http404 when it was not found, we printed an error code and a message on the screen, because we now provide API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Zgs8zm9LAmI5bTT36k2FcA.gif" /></figure><p>Let’s write our code that lists all the books.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b8fecf3ab9009f71d6b044b79929d70/href">https://medium.com/media/7b8fecf3ab9009f71d6b044b79929d70/href</a></iframe><p>Before moving on to the React section, let’s use the API we created with JavaScript. We don’t always have to use react after all. <br>Our process is to write a very simple JavaScript code. We will send an Http request and print the returned data on the screen. We use the code below to print all the books we have on the homepage as a list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02c6d3f70b1e603850145b8e37030bd3/href">https://medium.com/media/02c6d3f70b1e603850145b8e37030bd3/href</a></iframe><p>I didn’t do anything about styling because our aim is to understand the main idea.</p><p>We did book creation page with book_create_view function and it creates a form according to model rules. Let’s create our own form and send it to API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74997df4bdaac5ec96490a35b723c0e0/href">https://medium.com/media/74997df4bdaac5ec96490a35b723c0e0/href</a></iframe><p>After adding the form into home page, fill the form and click the save button. Yes, you see an error message as CSRF verification failed. Request aborted.</p><p>When we created our first form we sent a csrf_token. We should apply the same thing here also. We add our {% csrf_token %}code inside the form. After adding it, we made our form working.</p><p>Now it stays in the same page after saved our form but it’s better to redirect to the previous page. We already prepared our plan in the above code by adding an input named next. We’ll use that as a redirection page if creation is done. Let’s call the redirect argument from the django.shortcuts library to our view page ( from django.shortcuts import render, redirect). We will use our incoming ‘next ’ value as the page to be redirected and, if the recording has occurred, we will redirect it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa66d88bd39a994333f9c5cbe372b74/href">https://medium.com/media/baa66d88bd39a994333f9c5cbe372b74/href</a></iframe><p>n order to take a little precaution, let’s make sure that the address to be routed is secure. If somehow a different address is sent inside as the next value, the user will not be directed to an unwanted address. To do it, let’s add our secure addresses to the settings.py file with the ALLOWED_HOSTS array.</p><pre>ALLOWED_HOSTS = [&#39;127.0.0.1&#39;, &#39;yourdomainname.com&#39;, &#39;localhost&#39;]</pre><p>To be able to check these addresses, we’ll use Django’s features. Import the is_safe_url from django.utils.http import is_safe_url code to the page. This code will check the page which wanted to redirect is safe or not by comparing the URLs in ALLOWED_HOSTS and the redirection page.</p><p>We add another check to the line where we control if next_url != None and save it as if next_url != None and is_safe_url(https://medium.com/next_url) . When we run this form and submit form, we will see an error, because we did not call our settings to the page and show our accepted addresses. We import our settings to our page with from django.conf import settings . Within the page, we define ALLOWED_HOSTS = settings.ALLOWED_HOSTS variable and send it as the second parameter into is_safe_url() (next_url, ALLOWED_HOSTS) .The final version of our view code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/406b38c580898bbb3555f7f4a8dd9d75/href">https://medium.com/media/406b38c580898bbb3555f7f4a8dd9d75/href</a></iframe><p>To test our is_safe_url code, you may change any other address as next value via form.</p><h4>Serializer</h4><p>The serialization process is the process of converting the class or objects that we have into the format to be stored or sent. In cases where we do not know the types of objects or classes we have registered, we can increase the usability for later use by serializing. This process will bring increased performance and our data to shrink.</p><p>Let’s install djangorestframework, the django library which will enable us to play on the REST API and help us with serialization, by writing pipenv install djangorestframework code on the console and install it in our project. Add rest_framework to our INSTALLED_APPS array in settings.py file. We can now use this library by calling our page.</p><p>Actually, we did the serialization process since we definebooks = [{&#39;id&#39;:x.id, &#39;name&#39;:x.name, &#39;author&#39;:x.author, &#39;description&#39;: x.description} for x in blist] and now separating this process let’s add some little changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6810a3c3117c2a17bf68332b618d02/href">https://medium.com/media/4e6810a3c3117c2a17bf68332b618d02/href</a></iframe><p>After defining serialize function inside of Model, we can clarify books_list view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec661cdab162a26383c3b4feeb2e743/href">https://medium.com/media/2ec661cdab162a26383c3b4feeb2e743/href</a></iframe><p>Now we have got rid of the code clutter we had while defining our variable.</p><p>We did book creation process by using Form before. Now let’s rewrite it with the serialization process in djangorestframework. Create a file named serializer.py and adapt the code we wrote in form.py here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/770098d8ed5e36cead43949fe66aa24e/href">https://medium.com/media/770098d8ed5e36cead43949fe66aa24e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f358cfb9d4d06b3bf49aa1b5c48abd4e/href">https://medium.com/media/f358cfb9d4d06b3bf49aa1b5c48abd4e/href</a></iframe><p>Serializer file ready-to-use so we’ll use it in view side.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c8b4776e5e37dfc0f3b4dd605a3d6cd/href">https://medium.com/media/8c8b4776e5e37dfc0f3b4dd605a3d6cd/href</a></iframe><p>I changed book_create_view function we created earlier by adding _pure. I rewrote this function with the serializer I created. Previously we had rendered an html file. Now, we have printed our return result as json to be able to use the results on the front-end side.</p><p>Let’s roll out from Django Views to Django Rest Framework Views starting from changing book_create_view function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3fd62bb39e0e709c3c3011edf964ad1/href">https://medium.com/media/f3fd62bb39e0e709c3c3011edf964ad1/href</a></iframe><p>Adding the@api_view() code above our function, we provide the function view as an API. We can determine the accessibility of this function by giving parameters such as POST-GET. Our return method is Response instead of JsonResponse now.</p><p>That’s all! — not, of course. Well, we’ve learned what we need to keep practicing so far. To learn more about Djangorestframework you may visit its documentation page, you can learn which parameters you can use.</p><h3>Tests</h3><p>The last operation will be done on django side is testing. Even you have never done testing before, it’s time to take a step to TDD(Test Driven Development). If we get used to doing this — even if it’s in another language — it will save us time.</p><p>When we install our application, it brings our test file with it. When we write ./manage.py tests books on the command line, it will run our test and our first output will be as follows:</p><pre>System check identified no issues (0 silenced).</pre><pre>----------------------------------------------------------------------<br>Ran 0 tests in 0.000s</pre><pre>OK</pre><p>The results are incredible, because there is no test code in our file. Hoping to keep this incredibly we keep moving. Let’s write a test code for Books model into tests.py file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad81dc7ed1ab5fdcb4ca2f6b11a17367/href">https://medium.com/media/ad81dc7ed1ab5fdcb4ca2f6b11a17367/href</a></iframe><p>In this case, we created a book and when we run the test it will create a new book and will be tested its id. If it did not save it or the data its saved is different than it should be, it will show up an error message.</p><pre>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.<br>----------------------------------------------------------------------<br>Ran 1 test in 0.003s</pre><pre>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>It ran successfully. If we have done self.assertEqual(book_obj.id, 5) it would show up an error as AssertionError: 1 != 5 when we run our test. While doing this for the first time, the first data given to database should have id 1, we say check it for 5. The same error would come even if the id of the created object is not 1. You can see more usages of Django’s documentation on testing.</p><p>Well, after we did everything how we can deploy our project? In this case, there’s information in almost every service providers’ pages. I’ll give you resources directly since it has no side can be interpreted. You may run Django in cloud-based platforms. The most popular about it is Heroku. You may publish your first project by following its own instructions. If you want to use your own server there are instructions on DigitalOcean. These processes will be exactly same in servers you can access with ssh.</p><p>So far, we have completed the operations we will do with Django. Adding books, listing, and printing the required book on the screen. I did not add the repetitive codes to avoid extending the article. Of course, not everything ends with this much. There is an alternative to every line of code we write. Each title goes deeper within itself. Starting with the simplest, we will continue to improve ourselves with plenty of practice. You can see the source codes I use in this article on <a href="https://github.com/baris5d/DjangoReact">Github</a>, and contribute if you wish.</p><p>You can contact me if you have any questions or about anything you need via my <a href="https://twitter.com/baris5d">Twitter </a>account.</p><p>I also have another article which is a continuation of this article named <a href="https://medium.com/@baris5d/full-stack-with-django-and-react-react-afae36017852">Full-Stack with Django and React — React</a>.</p><p>Happy codding! :)</p><p>Github, Twitter, Instagram: @baris5d</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dcd87d57356" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/full-stack-with-django-and-react-django-4dcd87d57356">Full-Stack With Django and React — Django</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django ve React ile Full Stack — React]]></title>
            <link>https://medium.com/@baris5d/django-ve-react-ile-full-stack-react-d9b84b58df8e?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b84b58df8e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:17:03 GMT</pubDate>
            <atom:updated>2020-08-05T08:17:48.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django ve React ile Full Stack — React</h3><p>Bu yazı Django ve React Full Stack — Django yazısının devamı niteliğindedir. Eğer o kısmı okumadıysanız veya backend ortamınız hazır değil ise, Django kullanarak geliştirdiğim — geliştirirken notlarımı paylaştığım — yazıya <a href="https://medium.com/@baris5d/django-ve-react-ile-full-stack-django-8dcecf7e4ef"><strong>buradan</strong> </a>ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ikFbXGafVdsDDCJAzrvfBg@2x.png" /></figure><p>Biliyorum, çok kapsamlı bir başlık. Olabildiğince basit tutacağım.</p><p>Bu yazıda bir kitap uygulamasını, Full Stack olarak Django ve React kullanarak ilk kurulumdan son ürüne kadar yapacağız. Bir ürün üzerinde göstermek adına bir CRUD(Create,Read,Update,Delete) uygulamasını, güzel ve basit bir giriş-geliştirme-ürün serisi yapmayı umuyorum. İki taraftan da (back end ve front end) çok fazla bilgi karmaşasına boğmadan, çalışır bir uygulamayı elde ederken aldığım notları, izlediğim adımları sizlerle paylaşmak istiyorum.</p><p>Ne, nedir gibi sorular üzerinde çok durmamaya, sıkmadan, amaca yönelik anlatmaya çalışacağım. Kullandığım her komut için bilmeyenler olabilir diye link vereceğim, kendi dökümantasyon sayfalarından hızlı bir şekilde fikir sahibi olup yazıya geri dönebilirsiniz.</p><p><a href="https://www.djangoproject.com/">Django</a> kısaca Python tabanlı ücretsiz ve açık kaynak kodlu, model-template-view mimarisini temel alan bir web kütüphanesidir.</p><p><a href="https://reactjs.org/">React</a> web projelerinizin kullanıcı arayüzlerini, component bazlı olarak oluşturmanızı sağlayan bir JavaScript kütüphanesidir.</p><h3>Giriş #1</h3><p>Django ile backend yapımızı kurduk, HTML ile verilerimizi gördük. Şimdi işleri biraz daha kızıştırmanın zamanı geldi. O yazıyı hala okumadıysanız buradan okuyabilirsiniz.</p><p>Projemizin içerisinde React uygulamamızı kurarak başlayabiliriz.</p><h3>Kurulum</h3><p>Projemizin içerisine girip, komut satırınanpx create-react-app frontend kodunu yazarak kurulumumuzu başlatıyoruz. Frontend adında bir proje oluşturma sebebim, dosyaların birbirine girmeyip daha anlaşılır görünmesini istemem. Node dosyaları ve Django dosyaları ayrı klasörlerde olsun istiyorum ki erişmesi ve düzenlemesi kolay olsun.</p><p>Kurulum tamamlandıktan sonra cd frontend ve npm start komutlarını çalıştırıyoruz. Proje çalıştığında otomatik olarak http://localhost:3000/ adresini varsayılan tarayıcıda açacaktır. Açmazsa elle giriş yapabilirsiniz, 127.0.0.1:3000 adresinin de aynı yere ulaşacağını söylememe gerek yok diye düşünüyorum. Bu adresler dışında eğer farklı bir port üzerinden çalıştırırsa terminal ekranında erişim adresleri görünecektir.</p><h4>Ne kadar bilmem gerekiyor?</h4><p>Kurulumumuzu gerçekleştirdik fakat buradan sonrasına devam etmeden önce bilmemiz gerekenler var. Eğer ilk defa React ile karşılaşıyorsanız veya daha önce JavaScript yazmadıysanız, biraz zorlanabilirsiniz. Sadece React özelinde değil, JavaScript olarak ele alırsak: asenkron çalışan bir dile adaptasyon sağlamak bir miktar can sıkıcı olabiliyor. JavaScript tümüyle yukarıdan aşağıya doğru işlenen bir dil değildir. Altta yazdığınız kod en üstte yazdığınızdan daha önce çalışırsa çok şaşırmayın. O yüzden en azından JavaScript başlangıcı yapmanız sizin için faydalı olacaktır. <a href="https://javascript.info/">https://javascript.info/</a> adresinde başlıklar halinde güzel bir şekilde anlatılmış. En azından yazının ilerleyen zamanlarında okuduğunuzu anlayabilecek kadar bilgi edinmeniz, yazının devamında işinizi kolaylaştıracaktır.</p><h4>Fonksiyonel Bileşenler(Functional Components)</h4><p>Arayüzümüzü tasarlarken fonksiyonel bileşenler(functional components) kullanacağız. Tercih etme sebebimiz kodumuzun okunabilirliği, yenilenebilirliği ve test edilebilirliği açısından bize kolaylıklar sağlaması.</p><p>Class Components ve Functional Components farkları gibi şeylere fazla değinmek istemiyorum. Sadece bu ikisinin farkı ile ilgili bile, sağladığı faydalar/zararlar ile ilgili inceleme yapmak hedefimizden şaşırtacaktır bizleri. O sebepten, bu konuda ayrı bir inceleme yapmak isterseniz aşağıdaki linki takip edebilirsiniz.</p><p>Fonksiyon ve Sınıf Bileşenleri : <a href="https://tr.reactjs.org/docs/components-and-props.html">h</a>ttps://tr.reactjs.org/docs/components-and-props.html</p><p>Bileşen tabanlı geliştirme fikri bizi kod fazlalığı ve dağınıklığından kurtaracak.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2845becd237ec18edf55f69abd13355/href">https://medium.com/media/d2845becd237ec18edf55f69abd13355/href</a></iframe><p>İlk kurulumda karşımıza gelen en basit fonksiyonel bileşenimiz bu şekilde. Fonksiyonumuz return değeri olarak bir dom hazırlıyor ve gönderiyor. Temiz ve basit görünüyor değil mi? Bu fonksiyona kitap listemizi düzenli bir şekilde bastırabileceğimiz elementlerimizi eklemeye başlayabiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e55c7f91ca26dbfc34d2a1700dcdea4/href">https://medium.com/media/8e55c7f91ca26dbfc34d2a1700dcdea4/href</a></iframe><p>Fonksiyonumuzun döndürüğü elementleri ihtiyacımız olan şekilde değiştirdik. Basit bir html bilgisi ile bunu yaptık. React kullanırken yaptığımız tek fark class isimlerini verirken kullandığımız className parametresi oldu — şimdilik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*RcXfQNkP4bKpTeaGNGV4kQ.png" /><figcaption>Ekran</figcaption></figure><h4>Hooks — useEffect ve useState</h4><p>Hooks React’ın 16.8~ sonrası kullanıma sunduğu, sınıf kullanmadan React özelliklerini kullanmamıza olanak sağlayan yapı. (<a href="https://reactjs.org/docs/hooks-intro.html#no-breaking-changes">https://reactjs.org/docs/hooks-intro.html#no-breaking-changes</a>)</p><p>React lifecycle’ında componentDidMount , componentDidUpdate ve componentWillUnmount metodları yer alıyor. Hooks ile artık bu metodları useEffect kullanıyoruz.</p><p>Import işlemlerimizi yaparak işe koyulalım.</p><pre>import {useState, useEffect } from &#39;React&#39;</pre><p>Fonksiyonumuz içerisinde ilk state’imizi tanımlayalım.</p><pre>const [books, setBooks] = useState([])</pre><p>booksadında bir state tanımlayıp içerisine varsayılan olarak boş bir dizi gönderdik. Bu işlem sınıf bileşenlerinde şu şekildeydi:</p><pre>class Test extends React.Component{<br>  constructor(props){<br>    super(props)<br>    this.state = {<br>      books : []<br>    }<br>  }<br>}</pre><p>Fonksiyonel bileşen kullanmanın ilk faydasını da böylelikle görmüş olduk.</p><p>Şimdi de bu state’imizin içerisine bir veri yollayıp kullanmayı deneyelim. Bu işlem için de useEffect kullanacağız.</p><pre>useEffect (() =&gt; {<br>    setBooks([<br>         {<br>           &quot;name&quot;:&quot;Otostopçunun Galaksi Rehberi&quot;, <br>           &quot;author&quot;:    &quot;Douglas Adams&quot;, <br>           &quot;description&quot;: &quot;Lorem ipsum&quot;<br>         },<br>         {<br>           &quot;name&quot;:&quot;Hikayeler&quot;, <br>           &quot;author&quot;:    &quot;Edgar Allan Poe&quot;, <br>           &quot;description&quot;: &quot;Lorem ipsum sit door amet&quot;<br>         }<br>      ])<br>},[])</pre><p>books state’in içerisine iki adet veri yerleştirdik. Bu verileri JSX içerisinde bir döngüye sokarak ekrana bastıralım. Bu işlemi de Array.prototype.map kullanarak yapacağız.</p><pre>books.map((<em>book</em>,<em>index</em>) =&gt; {<br>   return (<br>     &lt;div <em>className</em>=&quot;book-item&quot;&gt;<br>       &lt;h2&gt;{<em>book</em>.name}&lt;/h2&gt;<br>       &lt;p&gt;{<em>book</em>.author}&lt;/p&gt;<br>       &lt;p&gt;{<em>book</em>.description}&lt;/p&gt;<br>    &lt;/div&gt;<br>   )}<br>)}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Zxomqfu3w5l3MbEDfwYWDw.png" /></figure><p>Kodumuzu çalıştırdığımızda artık ekranda elimizdeki verileri görebiliyoruz. Fakat biz bu verileri django ile hazırladığımız API’den alacağız. Django tarafında pure javascript ile XMLHttpRequst işlemi ile verilerimizi almıştık. Yine aynı kodu çalıştırabiliriz fakat bir adım daha ileriye giderek bu sefer farklı bir adresten de veri almamızı sağlayan Fetch API kullanacağız.</p><h4>Fetch API</h4><p>Django ile hazırladığımı REST API üzerinden verilerimizi alacağız. Eğer bu seriyi başından beri okumadıysanız ve farklı bir backend altyapısı kullanıyorsanız da bu işlem aynı olacaktır.</p><p>useEffect içerisinde kitaplarımızı tanımladığımız kısmı silip yerine API’ye bir istek atıp oradan gelen verilerimizi ekleyen kodumuzu yazacağız.</p><pre>useEffect (() =&gt; {<br>   async function fetchBooks() {<br>     const res = await fetch(&quot;http://127.0.0.1:8000/books/&quot;);<br>     res.json()<br>    .then(<em>res</em> =&gt; setBooks(<em>res.response</em>))<br>    .catch(<em>err</em> =&gt; setErrors(<em>err</em>));<br>   }<br>   fetchBooks();<br>},[])</pre><p>Async fonksiyon hakkında daha fazla bilgiye <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">bu adresten</a> ulaşabilirsiniz. Fakat basit bir örnek ile açıklamak gerekirse:</p><pre>getBooks = () =&gt; {<br>    console.log(&#39;first book&#39;);    <br>    setTimeout(() =&gt; {<br>        console.log(&#39;second book&#39;);    <br>},3000);    <br>console.log(&#39;third book&#39;);}</pre><pre>getBooks ();</pre><p>JavaScript, senkron ve single-thread yapıya sahiptir. Yukarıdaki kodda first book çıktısını verdikten sonra third book ve sonra 3 saniye bekleyip second book çıktısını ekrana verecektir. Biz o 3 saniyeyi beklemesini istediğimiz için async fonksiyon kullanımını tercih ettik. Async yapı içerisinde await’i de barındırdığı için bir işlemi tamamlamadan diğerine geçmesini engellemiş oluyoruz.</p><p>Şimdi react tarafına dönecek olursak (Django ve React’ın çalıştığını varsayıyorum) tarayıcıyı açtığımızda karşımıza şöyle bir ekran gelecek:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*1j17_KBVzWenfiWS6OIhrw.png" /></figure><h4>CORS Headers</h4><p>Açılımı Cross-Origin Resource Sharing(Kökenler arası kaynak paylaşımı) olan CORS Headers, bir kaynağın farklı bir kökende çalışan bir web uygulamasının erişim izinlerini kontrol eden mekanizmadır. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#:~:text=Cross-Origin%20Resource%20Sharing%20(CORS)%20is%20a%20mechanism%20that,resources%20from%20a%20different%20origin.&amp;text=The%20CORS%20mechanism%20supports%20secure,transfers%20between%20browsers%20and%20servers.">CORS</a>)</p><p>API kaynağımızın bu erişim iznini vermesi için Django tarafında bir yapılandırma gerçekleştirmemiz gerekiyor.</p><p>pipenv install django-cors-headers kodunu backend tarafında çalıştırarak django-cors-headers uygulamamızı kuruyoruz. Kurulum detaylarını <a href="https://pypi.org/project/django-cors-headers/">dökümantasyon</a> sayfasından inceleyebilirsiniz.</p><p>Kurulum tamamlandıktan sonra settings.py dosyamızda bulunan INSTALLED_APPS içerisine corsheaders ‘ı ekliyoruz ve MIDDLEWARE içerisine de &#39;corsheaders.middleware.CorsMiddleware&#39; kodumuzu ekliyoruz. Şimdi de hangi alanların erişebileceğini belirlememiz gerekiyor. Bunu iki şekilde yapabiliriz: bütün adresleri kabul ederek veya bir izin verilenler listesi vererek.</p><p>settings.py dosyamıza CORS_ORIGIN_ALLOW_ALL yazarsak isteyen bütün adresler verilerimize erişebilir. Sadece istediğimiz alanlarda sınırlandırmak istiyorsak:</p><pre>CORS_ORIGIN_WHITELIST = [<br>    &quot;https://example.com&quot;,<br>    &quot;https://sub.example.com&quot;,<br>    &quot;http://localhost:8080&quot;,<br>    &quot;http://127.0.0.1:9000&quot;<br>]</pre><p>şeklinde bir liste de belirleyebiliriz. Bunun dışında bir regex pattern’ı belirlememize de olanak sağlıyor.</p><p>Kaydetiğimizde API’dan gelen veriler artık tarayıcıda listelenebilecek.</p><p>Öyle ya da böyle çalıştırdığımıza göre biraz daha sadeleştirme işlemi yapabiliriz. Unutmayalım ki bileşen bazlı çalışıyoruz. Kitaplarımızı direkt döngü içerisinde ekrana bastırmıştık. Şimdi bu verilerimizi ayrı bir bileşen olarak ele alalım.</p><p>Book adında yeni bir fonksiyon oluşturup bunun return değerini kitaplarımızı listelediğimiz elementler olarak atıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a1da45d61f70209f6ca5176ed9190c8/href">https://medium.com/media/6a1da45d61f70209f6ca5176ed9190c8/href</a></iframe><p>Gelen prop’lar içerisinden book isimli prop’u aldık ve artık ekrana bastırabiliriz. App içerisindeki map kodumuzun arasına &lt;Book book={item} key={index} /&gt; kodunu eklediğimizde yine ekran çıktımız aynı şekli alacaktır.(book değişkeninin adını karışıklık olmaması için item olarak değiştirdim)</p><p>Tekrar eden değerler için React bizden bir seçici göndermemizi istediği için key içerisine index değerimizi gönderip çalıştırdık.</p><p>Şimdi de kitap ekleme sayfamızı React tarafına taşıyalım. Yeni bir bileşen oluşturup içerisine form elementlerimizi yerleştiriyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3042aa5424baad34178036c8c7f8cf0f/href">https://medium.com/media/3042aa5424baad34178036c8c7f8cf0f/href</a></iframe><h4>Axios</h4><p>Basit bir şekilde formumuzu oluşturduk. Formumuzu api içerisine post metodu ile göndermek için axios kullanacağız. Bunu yaparken yine React Hooks’tan faydalanacağız. Giriş değerlerimizi state içerisinde tutacağız ve formu kaydet butonuna bastığımızda gönderimi yakalayıp istediğimiz işlemleri axios ile yaptıracağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef8ab38442892b7fb97fd44a165b0b38/href">https://medium.com/media/ef8ab38442892b7fb97fd44a165b0b38/href</a></iframe><h4>CSRF Token</h4><p>Formu gönderdiğimizde bir şey kaydedemediğimizi göreceğiz, 400 hata kodu döndürecek. Bunun ilk sebebi backend kodumuz bizden csrf token bekliyor. <a href="https://docs.djangoproject.com/en/3.0/ref/csrf/">Dökümantasyon</a> sayfasında ajax ile nasıl csrf token gönderebileceğimiz bilgisi yer alıyor. Oradaki getCookie fonksiyonunu kodumuza ekliyoruz. axios ile de bu token bilgisini header ile gönderiyoruz. Varsayılan çerez adı csrftoken bunu dilerseniz settings.py sayfasından özelleştirebiliyorsunuz. React kodumuzu düzenlediğimizde aşağıdaki hali alıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4996567b97193b6c8ad3b9b8c4adcbe8/href">https://medium.com/media/4996567b97193b6c8ad3b9b8c4adcbe8/href</a></iframe><p>Yukarıdaki formumuzu gönderdiğimizde tarayıcının network ekranından artık csrftoken bilgisini gönderdiğimizi görebiliriz. Fakat o da ne!? Hala 400 Bad request dönüyor. Backend kodumuza gidip serialize ettiğimiz değeri kontrol ettiğimizde farkediyoruz ki kaydetmeye çalıştığımız değer boş. BooksSerializer(data=request.POST or None)</p><p>print(request.POST) kodu bize &lt;QueryDict: []&gt; çıktısını veriyor. Bizim artık ihtiyacımız olan değer request.POST değil, request.data Serialize ettiğimiz veriyi request.data ile değiştirip kodumuzu çalıştırdığımızda artık React tarafından verimizi gönderip kaydedebiliyoruz.</p><p>CSRF Token ile ilgili daha fazla parametre ve daha detaylı bilgi için <a href="https://docs.djangoproject.com/en/3.0/ref/csrf/">bu sayfayı </a>ziyaret edebilirsiniz.</p><h4>React Routing</h4><p>Son olarak da görmek istediğimiz kitaplara ait özel linkler olsun istiyoruz. Bu işlemleri yine tek bileşende elle yapabilirdim fakat basit bir router yapısı da kurmadan geçmek istemedim.</p><p>Öncelikle kurulum yaparak başlıyoruz: npm install react-router-dom</p><p>Ben kodları yazarken bütün bileşenleri tek sayfada yaptım, bunları ayrı ayrı sayfalar ve klasörler içerisinde yaparak import { ComponentName } from &#39;path/file&#39; şeklinde sayfaya dahil ederek &lt;ComponentName /&gt; şeklinde de kullanabilirsiniz. App bileşenimiz kitaplarımızı listeliyor ve üst tarafta da kitap oluşturma formumuzu gösteriyordu. Bu sayfaların hepsini birbirinden ayırarak basit bir router kuralım. App bileşenimiz kitapları listelediğimiz sayfa olarak kalsın. Sayfamızın sonundaki export default App kodunu da silelim varsayılan olarak o bileşenimiz renderlanmasın. Router yapımız şu şekilde:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3011e5c5068814c109ecde882fb86be/href">https://medium.com/media/b3011e5c5068814c109ecde882fb86be/href</a></iframe><p>Tabi benim gibi, önce kodu yazıp, kullandığınız kütüphaneleri sayfaya çağırmayı unutmayın.</p><pre>import {<br>  <em>BrowserRouter</em> as Router,<br>  Switch,<br>  Route,<br>  Link<br>} from &quot;react-router-dom&quot;;</pre><p>İlk açılacak sayfamız Landing bileşeni olacağı için index.js dosyasından çağırdığımız bileşeni de Landing olarak değiştiriyoruz.</p><p>Sayfayı yenilediğimizde sayfanın en üstünde liste şeklinde, oluşturduğumuz menü linklerini göreceğiz. Ana dizinde olduğumuz için de &lt;App/&gt; bileşeni çağırılacak ve kitaplarımız listelenecek.</p><p>Tekil kitap gösterme sayfamız için de kodumuzu yazalım. Bu işlem bütün kitapları listelediğimiz kodumuz ile aynı. Tek fark, back end tarafından bir status bilgisi gönderip ona göre eğer istenen kitap veritabanımızda yoksa hata mesajı göstereceğiz. Backend kodumuzu yazarken veri bulunamadıysa sayfamızın 404 döndürmesini istemiştik. Şuan header bilgileri ile çok haşır neşir olmamak adına dönen veriye bir durum kodu (“ok”,”error”) ekleyerek bunu kontrol ederek ekrana mesaj bastıracağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a716d45299352a495c82bd7b6e292d2/href">https://medium.com/media/9a716d45299352a495c82bd7b6e292d2/href</a></iframe><p>Artık localhost:3000/book/1 adresine girdiğimizde, eğer veritabanında 1 id’li bir veri var ise ekrana bastıracak. Bir hata oluşur veya durum kodumuz hatalı gelirse ekrana “Something went wrong” mesajını bastıracak.</p><p>Ana sayfada kitapları listelerken başlıklarını da link olarak ekleyelim, sayfalar arası gezintimiz rahat olsun.</p><p>Kitap listeleme kodumuzu şu şekilde değiştiriyoruz:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2d684e0302e2544c32ed0abe10b2f8a/href">https://medium.com/media/a2d684e0302e2544c32ed0abe10b2f8a/href</a></iframe><p>Evet, artık kitaplarımız listelenirken başlıklarına tıklayarak detay sayfalarına gidebiliriz.</p><p>Bütün işlerimizi tamamladıktan sonra optimize, yayına koyacağımız dosyalarımızı almak için npm run build komutunu çalıştırıyoruz ve build adında bir klasöre statik dosyalarımızı çıkartıyor.</p><p>Şuana kadar herhangi bir CSS kodu yazmadan düz bir şekilde çıktılarımızı gördük. İlerleyen zamanlarda görsel olarak da eklemeler yapacağım. Yazının niteliğini kaybetmemesi için, bir de bu tarafa doğru kapı aralayıp boğmak istemiyorum. Projenin son halini <a href="https://github.com/baris5d/DjangoReact">DjangoReact</a> linkinden inceleyebilir, dilerseniz katkıda bulunabilirsiniz.</p><p>Soru veya sorunlarınız için bana <a href="https://twitter.com/baris5d">Twitter </a>üzerinden ulaşabilirsiniz.</p><p>Happy codding! :)</p><p>Github, Twitter, Instagram : @bari5d</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b84b58df8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django ve React ile Full Stack —Django]]></title>
            <link>https://medium.com/@baris5d/django-ve-react-ile-full-stack-django-8dcecf7e4ef?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dcecf7e4ef</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:16:58 GMT</pubDate>
            <atom:updated>2020-08-05T08:18:14.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hiAOg-RRpXjBFAA06SDdpA@2x.png" /></figure><p>Biliyorum, çok kapsamlı bir başlık. Olabildiğince basit tutacağım.</p><p>Bu yazıda bir kitap uygulamasını, Django ve React kullanarak kurulumdan son ürüne kadar yapacağız. Bir CRUD(Create,Read,Update,Delete) uygulamasını, güzel ve basit bir giriş-geliştirme-ürün serisi yapmayı umuyorum. İki taraftan da (back end ve front end) çok fazla bilgi karmaşasına boğmadan, çalışır bir uygulamayı elde ederken aldığım notları, izlediğim adımları sizlerle paylaşmak istiyorum.</p><p>Ne, nedir gibi sorular üzerinde çok durmamaya, sıkmadan, amaca yönelik anlatmaya çalışacağım. Kullandığım her komut için bilmeyenler olabilir diye kaynak vereceğim, kendi dökümantasyon sayfalarından hızlı bir şekilde fikir sahibi olup yazıya geri dönebilirsiniz.</p><p><a href="https://www.djangoproject.com/">Django</a> kısaca Python tabanlı ücretsiz ve açık kaynak kodlu, model-template-view mimarisini temel alan bir web kütüphanesidir.</p><p><a href="https://reactjs.org/">React</a> web projelerinizin kullanıcı arayüzlerini, component bazlı olarak oluşturmanızı sağlayan bir JavaScript kütüphanesidir.</p><h3>Ortam Kurulumu #1</h3><p>Yazıya devam etmeden önce cihazınızda kurulu olması gerekenler şu şekilde:</p><pre><a href="https://www.python.org/">Python3</a></pre><pre><a href="https://pypi.org/project/pip/">Pip</a></pre><pre><a href="https://nodejs.org/en/">NodeJS</a></pre><p>Bu yazıyı yazarken Python 3.6~, pip 20.1.1, NodeJS 12.18.2 sürümlerini kullanıyorum. Referans aldığım betikler eğer farklı bir versiyonda çalışmaz veya hata verir ise sormaktan çekinmeyin.</p><p>Kendimize bir çalışma ortamı oluşturarak başlayalım. Klasör ismini ben DjangoReact yaptım. Klasör içerisine girerek pipenv kurulumumuzu yapacağız. Pipenv paketleme işlemlerini(bundler, npm, yarn, composer, etc.) Python dünyasına getiren bir araç. Otomatik olarak sanal ortam oluşturma ve yönetme imkanı sağlıyor.(yeni paketler yükleme/silme işlemleri)</p><p>Çalışma klasörümüze giriş yaptıktan sonra, aşağıdaki kodu komut satırına yapıştıralım.</p><pre>python3.6 -m pip install pipenv --upgrade</pre><p>Kurulum tamamlandıktan sonra, aşağıdaki kod ile sanal ortamımıza django 3.0.8(son sürüm) kurulumumuzu yapıyoruz.</p><pre>pipenv install --python 3.6 django==3.0.8</pre><p>Kurulum sonrası klasörümüz şu şekilde olmalı:</p><pre>DjangoReact<br>├── Pipfile<br>└── Pipfile.lock</pre><p>Virturalenv’i aktifleştirmek için pipenv shell kodunu çalıştırıyoruz.</p><p>Django projemizi oluşturmaya başlayabiliriz artık. Komut satırına django-admin yazdığınızda kullanabileceğiniz parametreleri listeler. Bizim şu anlık ilgilendiğimiz parametre startproject. Biz bulunduğumuz klasöre kurulum gerçekleştirmek istediğimiz için (yazı başlangıcında bir klasör oluşturmuştuk zaten) bulunduğumuz klasöre DjangoReact adında bir proje oluşturuyoruz.</p><pre>django-admin startproject DjangoReact .</pre><p>Klasörümüzün son hali bu şekilde:</p><pre>DjangoReact/<br>    manage.py<br>    DjangoReact/<br>        __init__.py<br>        settings.py<br>        urls.py<br>        asgi.py<br>        wsgi.py</pre><p>Buraya bir not düşmek istiyorum: proje ve uygulama farklı şeyler. startprojectve startapp kullanımları birbirinden farklıdır. Uygulama, belirli bir amaca hizmet eden web uygulamasıdır — blog, todolist, veritabanı kayıtları vs. Proje ise bir web sitesi içerisinde uygulama ve yapılandırma koleksiyonudur. Proje birden fazla uygulamayı içerisinde barındırabilir.</p><p>Kontrol etmek için sunucumuzu çalıştırıp, doğru çalıştığını kontrol ediyoruz. python manage.py runserver kodunu çalıştırdığımızda terminaldeki çıktı aşağıdaki gibi olmalı.</p><pre>(DjangoReact) $~ python manage.py runserver</pre><pre>Watching for file changes with StatReloader<br>Performing system checks…<br>System check identified no issues (0 silenced).</pre><pre>You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.<br>Run ‘python manage.py migrate’ to apply them.</pre><pre>July 17, 2020–14:22:01<br>Django version 3.0.8, using settings ‘backend.settings’<br>Starting development server at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a><br>Quit the server with CONTROL-C.</pre><p>Localhost’umuza girdiğimizde ise aşağıdaki ekran bizi karşılıyor. Evet! Çalıştı.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpdJoLREx2aIWdaiQ-M9dQ.png" /><figcaption>127.0.0.1</figcaption></figure><p>Son küçük bir dokunuşumuz kaldı. Onu da yapıyoruz…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4s_2PvMFQKSGjfLWBjXWw.png" /></figure><p>Evet! Artık CV’mize Django’yu da ekleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*qKHwBXKxuBUIQ4DH9NCRyQ.gif" /></figure><h3>Model, View, Routing…urls #2</h3><p>Şimdi ilk uygulamamızı oluşturma vaktimiz geldi. Yapılacaklar listemi şu şekilde yazdım:</p><pre>1. Books</pre><pre>-&gt; Creating</pre><pre>   -&gt; Name?</pre><pre>   -&gt; Author?</pre><pre>   -&gt; Description?</pre><pre>   -&gt; Image?</pre><pre>-&gt; Search</pre><pre>-&gt; Delete</pre><pre>-&gt; Update</pre><pre>2. Feed</pre><pre>-&gt; List of all books</pre><p>DjangoReact klasörünün içerisinde gelip ./manage.py startapp books komutu ile bir uygulama oluşturuyoruz. Komutu çalıştırdıktan sonra klasörümüzün içerisinde ‘books’ adında bir klasör oluşturup içerisine kurulumu gerçekleştirecek. Klasörümüzün son hali şu şekilde;</p><pre>DjangoReact/<br>├── books<br>│   ├── admin.py<br>│   ├── apps.py<br>│   ├── __init__.py<br>│   ├── migrations<br>│   │   └── __init__.py<br>│   ├── models.py<br>│   ├── tests.py<br>│   └── views.py<br>├── db.sqlite3<br>├── DjangoReact<br>│   ├── asgi.py<br>│   ├── __init__.py<br>│   ├── __pycache__<br>│   │   ├── __init__.cpython-36.pyc<br>│   │   ├── settings.cpython-36.pyc<br>│   │   ├── urls.cpython-36.pyc<br>│   │   └── wsgi.cpython-36.pyc<br>│   ├── settings.py<br>│   ├── urls.py<br>│   └── wsgi.py<br>├── manage.py<br>├── Pipfile<br>├── Pipfile.lock<br>└── todo.md</pre><h4>Model</h4><p>Oluşturduğumuz books uygulamasının içerisindeki model.py dosyasını aşağıdaki gibi yapılandırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157472e9eeb70810d68f1f0a3bd7d3e1/href">https://medium.com/media/157472e9eeb70810d68f1f0a3bd7d3e1/href</a></iframe><p>models.TextField() ile isim, yazar, açıklama alanlarını tanımlıyoruz. blank=False ve null=False yaptıklarım doldurulması gereken alanlarımız, diğerleri boş olsalar da kabul edeceğiz. id alanımız otomatik olarak artacak ve seçici olarak kullanılacağı için onu AutoField ve anahtar olarak tanımladık. Kapak fotoğraflarımızı alabilmek için de FileField kullanarak dosya yolu belirledik ve bu alan boş bırakılabilir dedik.</p><h4>Migrate</h4><p>Uygulamamızı, proje çalıştığında tanıyabilmesi için proje klasörümüz altındaki settings.py dosyasında INSTALLED_APPS dizisini bulup içerisine model ismimizi ekleyip kaydetmemiz gerekiyor &#39;books’. Bu işlemi yaptıktan sonra modelimizde yaptığımız değişiklikleri veritabanı şemasına yazmak için ./manage.py makemigrations komutunu çalıştırıyoruz ve tamamlandıktan sonra python manage.py migrate komutunu ile yaptığımız değişiklikleri uyguluyoruz.</p><pre>$~ ./manage.py makemigrations</pre><pre><strong>Migrations for &#39;books&#39;:</strong><br>  books/migrations/0001_initial.py<br>    - Create model Books</pre><pre>$~ python manage.py migrate</pre><pre><strong>Operations to perform:</strong><br>  Apply all migrations: admin, auth, books, contenttypes, sessions<br><strong>Running migrations:</strong><br>  Applying contenttypes.0001_initial... OK<br>  Applying auth.0001_initial... OK<br>  Applying admin.0001_initial... OK<br>  Applying admin.0002_logentry_remove_auto_add... OK<br>  Applying admin.0003_logentry_add_action_flag_choices... OK<br>  Applying contenttypes.0002_remove_content_type_name... OK<br>  Applying auth.0002_alter_permission_name_max_length... OK<br>  Applying auth.0003_alter_user_email_max_length... OK<br>  Applying auth.0004_alter_user_username_opts... OK<br>  Applying auth.0005_alter_user_last_login_null... OK<br>  Applying auth.0006_require_contenttypes_0002... OK<br>  Applying auth.0007_alter_validators_add_error_messages... OK<br>  Applying auth.0008_alter_user_username_max_length... OK<br>  Applying auth.0009_alter_user_last_name_max_length... OK<br>  Applying auth.0010_alter_group_name_max_length... OK<br>  Applying auth.0011_update_proxy_permissions... OK<br>  Applying books.0001_initial... OK<br>  Applying sessions.0001_initial... OK</pre><p>Oluşturduğumuz modelimizi terminal ekranında test edelim bakalım nasıl görünüyor. ./manage.py shell yazıp projemizi çalıştırıyor ve ekrana aşağıdaki kodları sırasıyla yazıyoruz;</p><pre>&gt;&gt;&gt; from books.models import Books<br>&gt;&gt;&gt; obj = Books()<br>&gt;&gt;&gt; obj.name = &quot;Otostopçunun Galaksi Rehberi&quot;<br>&gt;&gt;&gt; obj.author = &quot;Douglas Adams&quot;<br>&gt;&gt;&gt; obj.description = &quot;Uzaylı gören masum köylü&quot; # null veya blank olabilir dediğimiz için bu kısmı boş geçebilirsiniz.<br>&gt;&gt;&gt; obj.save()<br>&gt;&gt;&gt; exit()</pre><p>Yukarıdaki kodu çalıştırdık ve shell’den çıktık. Şimdi tekrar shell’e girip kaydımız gerçekleşmiş mi, veriyi çekebiliyor muyuz ona bakalım.</p><pre>&gt;&gt;&gt; from books.models import Books<br>&gt;&gt;&gt; firstBook = Books.objects.get(id=1)<br>&gt;&gt;&gt; firstBook.name<br>&#39;Otostopçunun Galaksi Rehberi&#39;<br>&gt;&gt;&gt; exit()</pre><h4>View</h4><p>Elbette bu şekilde terminal üzerinden devam etmeyeceğiz. Biraz da view tarafını kurcalayalım.’books’ klasörümüzün altındaki views.py dosyasını açalım ve bir ritüeli gerçekleştirmek adına ekrana Hello World yazdıralım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e75b8b33ecefea5e0a4124dd11d9a33d/href">https://medium.com/media/e75b8b33ecefea5e0a4124dd11d9a33d/href</a></iframe><p>Projemiz içindeki urls.py dosyasına da ana sayfamızı aşağıdaki gibi tanımlıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f3814e99e0a1373aac8a7a735ce181/href">https://medium.com/media/30f3814e99e0a1373aac8a7a735ce181/href</a></iframe><p>Tahmin etmesi güç biliyorum. http://127.0.0.1 adresine girdiğimizde kim bilir karşımıza ne çıkacak. Tadınızı kaçıran bir espriydi evet. Ekranda yine Hello World! yazımızı gördük.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*oas76xwNnP_JALfHYKDlSQ.gif" /></figure><h4>Dinamik URL’ler</h4><p>View dosyamız içerisine book_detail_view adında bir fonksiyon daha ekleyip, url üzerinden gelen parametreleri ekrana bastırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f810f3ee0799a8ae275ea7ec4af020/href">https://medium.com/media/d3f810f3ee0799a8ae275ea7ec4af020/href</a></iframe><p>Elbette ki henüz bu kısmı tetikleyen bir url yakalayıcımız yok. urls.py dosyamız içerisindeki book.view importumuza book_detail_view fonksiyonunu ekleyip, urlpatterns dizimize path(&#39;books/&lt;int:book_id&gt;&#39;,book_detail_view) kodunu ekliyoruz.</p><p>http://127.0.0.1:8000/books/1 adresine girdiğimizde ekranda Hey 1 başlığını göreceğiz. Parametre olarak girdiğimiz herhangi bir değeri sayfa içerisinde ekrana basabiliyoruz artık. Hadi bu gelen parametreyi kullanarak veritabanımızda bulunan kitap bilgilerini ekrana yazdıralım.</p><p>from .models import Books kodunu views.py dosyamıza ekleyelim. book_detail_view fonksiyonumuz içerisinde gelen book_id değerini alıp o id’ye ait bilgileri alıp ekrana bastıralım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e220186cafb66752a06b2e113f0017c/href">https://medium.com/media/6e220186cafb66752a06b2e113f0017c/href</a></iframe><p>Şimdi http://127.0.0.1:8000/books/1 adresine girdiğimizde ekranda çıktımız şu şekilde olacak:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*FMKDVMRA5zdHrg8yCCLKUw.png" /></figure><p>Veritabanımızda bulunmayan bir id girişi yaptığımızda, veritabanında böyle bir veri bulunamadığına dair hata ile karşılaşacağız. Bu hatayı da yakalayıp standart 404 sayfamızı döndürelim.</p><p>book_detail_view fonksiyonumuzdaki obj tanımlamasını try-except ile kontrol altına alalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56086be7e08ed4af682e050f5d1c1e26/href">https://medium.com/media/56086be7e08ed4af682e050f5d1c1e26/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*MpiPax6jRj-OLygpMd_ZWw.png" /><figcaption>Standart 404 sayfası</figcaption></figure><p>CRUD uygulaması yapacağız dedim fakat sadece R(read) kısmını yaptım. C(create) kısmı için bir form oluşturalım. /templates/components/form.html adında bir dosya oluşturuyoruz ve o boş bir şekilde beklerken uygulamamızın altına bir de form.py adında dosya oluşturup formumuzu tasarlamaya başlayalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cfe20b4812bd82dcfb5a6de7aa01e96/href">https://medium.com/media/7cfe20b4812bd82dcfb5a6de7aa01e96/href</a></iframe><p>Yukarıdaki kodu form.py dosyamızın içerisinde yazdık. Projeye başlarken model oluşturduğumuzda name, author, description alanlarını TextField yapmıştık. Django’nun ‘forms’ sınıfını çağırarak oluşturduğumuz modelde, istediğimiz verilere göre bir form oluşturmasını istiyoruz. Kitap açıklamasını da sınırlandırarak veriler üzerinde nasıl kontrol yapabileceğimizin örneğini vermiş olmak istedim. İlerlerken Django’nun da nimetlerinden faydalanmak lazım.</p><p>Şimdi views kısmında bu formu kullanabiliriz. book_create_view adında bir fonksiyon oluşturup create-book url’si geldiğinde bu fonksiyonu çalıştırması için urls.py dosyamıza ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c370e01deacc7db4e3cff48739523ec3/href">https://medium.com/media/c370e01deacc7db4e3cff48739523ec3/href</a></iframe><p>Yukarıdaki kodda, form.py dosyamızdan BooksForm sınıfını çağırdık. Model oluştururken hangi verilerin zorunlu, hangilerinin zorunlu olmadığını belirtmiştik. Buna göre Django’nun form sınıfından kontrol sağlıyoruz, eğer beklenen veriler dışında bir veri girişi yoksa gelen formu kaydediyoruz. Bu view POST ile ya da direkt url aracılığıyla görüntülenebilir. POST geldiği zaman yapacağı davranışı form = BooksForm(request.POST or None) kısmında belirttik.</p><p>Şimdi de arayüz tarafındaki karşılığını görelim. form.html dosyamız şu şekilde;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc5111acbe7160bd33fea3fa3bb3dcc/href">https://medium.com/media/cfc5111acbe7160bd33fea3fa3bb3dcc/href</a></iframe><p>form.as_p her elementi bir &lt;p&gt; tagı ile çerçevele anlamına geliyor. CSRF ise bir web uygulamasında oturum açan kullanıcının oturumu üzerinden kullanıcının istekleri dışında işlem yapılması durumudur. Kullandığımız token ise bunu engellemek adına oluşturulan bir hash’tir ve backend tarafında kontrol edilir. Konudan bağımsız faydalı bir bilgi.</p><p>Silme ve güncelleme işlemleri için tekrar bir açıklama yapmak istemedim, laf kalabalığı olmaması açısından. Kaydetme ve okuma işlemlerinden farklı değiller. Silmek için Books.object.filter(id=book_id).delete() kodunu kullanıyoruz. Güncelleme işlemi için ise okuma işlemi ile aynı.</p><pre>book = Books.object.get(id=1)<br>book.name = &quot;Yeni isim&quot;<br>book.save()</pre><h3>Templates, REST API, Djangorestframework ve Tests #3</h3><p>Şimdi elimizdeki verileri bir HTML Template dosyasının içerisine göndererek daha düzenli bir şekilde ekrana bastırmayı sağlayacağız.</p><h4>Template</h4><p>Öncelikle template klasörümüzü hazırlıyoruz. Ana dizine templates adında bir klasör oluşturuyoruz. Template yolunu belirleyebilmek için ise settings.py dosyamızda TEMPLATES dizisini bulup &#39;DIRS&#39; içerisini [os.path.join(BASE_DIR, &quot;templates&quot;)] olarak düzenliyoruz. Artık template yolumuzu belirttik. Templates klasörümüz içerisine /pages/home.html adında bir HTML dosyası oluşturuyoruz ve içerisine o dosya olduğunu belirten herhangi bir şey yazabilirsiniz. Ben “Hello World from home.html file” yazdım. Sonrasında, views kısmında ana sayfayı tanımladığımız home_view fonksiyonunun içerisini direkt ekrana bastıracak şekilde değil de HTML dosyamızı çağıracak şekilde yapılandırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f987468ee628d1ec8f4817f6ff64d9a/href">https://medium.com/media/4f987468ee628d1ec8f4817f6ff64d9a/href</a></iframe><p>Tekrar tekrar aynı kodları yazmaktan kaçınmak adına templates dizinimize bir adet base.html dosyası oluşturup, bütün sayfalarda kullanacağımız meta tagleri, başlık seçimleri gibi şeyleri tek bir dosyada tutuyoruz. Örnek olarak:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac0cf1af8381efc37e1f53185c20516/href">https://medium.com/media/bac0cf1af8381efc37e1f53185c20516/href</a></iframe><p>Daha önce twig, blade gibi tasarım motorları kullandıysanız bu fikir size uzak gelmeyecektir. Kullanmadım diyorsanız hızlı bir şekilde dökümantasyon sayfalarına gidip basit kullanımlarını inceleyebilirsiniz. Basit bir şekilde açıklamak gerekirse tasarım motorları, dinamik sayfalar içerisinde, backend tarafından gelen verileri derleyebilmemizi, parçalara ayırdığımız — menu,header,meta tags, sidebar vs. — dosyalarımızı ihtiyacımıza göre çalıştırmamızı sağlıyor. Konuyu dağıtmadan devam ediyorum.</p><p>Oluşturmuş olduğumuz base.html sayfasını home.html sayfasında değerlendireceğiz. home.html sayfamızı aşağıdaki gibi düzenliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a11e133ef7f2c79d5a310a72fa08b0/href">https://medium.com/media/25a11e133ef7f2c79d5a310a72fa08b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*tGvDzsiKrMI0iQh_qoncQQ.png" /></figure><p>Yukarıda gördüğünüz gibi ana sayfaya girdiğimizde artık home.html sayfamızı çağırıyor. Sayfa derlendiğinde ise yukarıda bahsettiğim gibi base.html içerisine entegre edilerek bu şekilde bir çıktı elde ediyoruz.</p><h4>REST API — DjangoRestFramework</h4><p>Template’imizi çalıştırdık, biraz karıştırdık. Şimdi ise elimizdeki verileri json verisi olarak döndürelim. book_detail_view ve home_view kısmında return değerimizi HttpResponse olarak yapmıştık. home_view’de sayfamızı HTML üzerinden renderladık, book_detail_view kısmında ise direkt olarak ekrana bastırdık. django.http içerisinden JsonResponse classını çağırıyoruz. Verilerimizi direkt olduğu gibi değil de biraz daha kullanışlı halleri ile bastıracağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c50bf0036095c816f64065d457d34ad7/href">https://medium.com/media/c50bf0036095c816f64065d457d34ad7/href</a></iframe><p>Yukarıdaki kodda, aranan veri bulunduysa data içerisine verilerini yazdık bulunamadıysa bir hata mesajı verdirttik. Bulunamadığında Http404 döndürmek yerine bir hata kodu ve mesaj bastırdık ekrana. Çünkü artık API sağlıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Zgs8zm9LAmI5bTT36k2FcA.gif" /></figure><p>Elimiz kirlenmişken tüm kitapları listeleyen kodumuzu da yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b8fecf3ab9009f71d6b044b79929d70/href">https://medium.com/media/7b8fecf3ab9009f71d6b044b79929d70/href</a></iframe><p>React kısmına geçmeden önce oluşturduğumuz API’yi JavaScript ile kullanalım. Her zaman react kullanmak zorunda değiliz sonuçta. Basit uygulamalarda basit çözümler üretelim.</p><p>Yapacağımız işlem son derece basit bir JavaScript kodu yazmak. Bir Http isteği atacağız ve dönen verileri ekrana basacağız. Ana sayfa üzerinde elimizdeki bütün kitapları liste olarak bastırmak için aşağıdaki kodu kullanıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02c6d3f70b1e603850145b8e37030bd3/href">https://medium.com/media/02c6d3f70b1e603850145b8e37030bd3/href</a></iframe><p>Amacımız genel yapıyı anlamak olduğu için tasarımsal olarak herhangi bir düzenleme yapmadım. Belki son aşamada küçük dokunuşlar ile güzel bir görüntü yakalarız.</p><p>Kitap ekleme sayfamızı book_create_view ile yapmıştık. Şimdi formumuzu kendimiz oluşturup, eklemek istediğimiz verileri API’ye gönderelim. Ekleme işlemlerini direkt ana sayfa üzerinden yapıp create-book adresine gönderelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74997df4bdaac5ec96490a35b723c0e0/href">https://medium.com/media/74997df4bdaac5ec96490a35b723c0e0/href</a></iframe><p>Ana sayfaya yukarıdaki formu ekleyelim. Formu doldurup kaydet butonuna bastığımızda CSRF verification failed. Request aborted. hatası alacağız. Formu ilk oluşturduğumuzda bir csrf_token göndermiştik. Aynısını burada da uygulamamız lazım. Formun içerisine {% csrf_token %} kodumuzu ekliyoruz. Ekledikten sonra formumuzu çalışır hale getirdik.</p><p>Ekleme işlemimiz gerçekleştiğinde adresimiz /create-book şeklinde kalacak. Ekleme işlemi başarıyla gerçekleştiyse ana sayfaya yönlendirme yapalım. next girişini bunun için aldık. View sayfamıza django.shortcuts kütüphanesinden redirect argümanını çağıralım( from django.shortcuts import render, redirect ). Gelen next değerimizi yönlendirilecek sayfa olarak kullanacağız ve eğer kayıt gerçekleştiyse yönlendireceğiz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa66d88bd39a994333f9c5cbe372b74/href">https://medium.com/media/baa66d88bd39a994333f9c5cbe372b74/href</a></iframe><p>Küçük bir önlem almak adına, yönlendirilecek adresin güvenli olduğundan emin olalım. Bir şekilde içeriye next değeri olarak farklı bir adres gönderilirse kullanıcı istenmeyen bir adrese yönlendirilmesin. Bunun için settings.py dosyamıza ALLOWED_HOSTS dizisi ile güvenli adreslerimizi ekleyelim.</p><pre>ALLOWED_HOSTS = [&#39;127.0.0.1&#39;, &#39;yourdomainname.com&#39;, &#39;localhost&#39;]</pre><p>Bu adresleri kontrol edebilmek için Django’nun sağladığı özelliklerden faydalanacağız. Sayfaya from django.utils.http import is_safe_url kodumuzu ekliyoruz. Bu kod ayarlara eklediğimiz kabul edilen adresler ile yönlendirilmek istenen sayfayı karşılaştırarak, güvenli olup olmadığını kontrol edecek. if next_url != None kontrolü yaptığımız satıra bir kontrol daha ekliyoruz ve son hali if next_url != None and is_safe_url(https://medium.com/next_url) olacak şekilde kaydediyoruz. Bu haliyle çalıştırıp bir form gönderdiğimizde artık hata ile karşılaşacağız. Çünkü ayarlarımızı sayfaya çağırıp kabul edilen adreslerimizi göstermedik. from django.conf import settings ile ayarlarımızı sayfamıza çağırıyoruz. Sayfa içerisinde ALLOWED_HOSTS = settings.ALLOWED_HOSTS değişkenimizi tanımlıyor ve is_safe_url() içerisine ikinci parametre olarak gönderiyoruz is_safe_url(https://medium.com/next_url,%20ALLOWED_HOSTS)</p><p>View kodumuzun son hali şu şekilde:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/406b38c580898bbb3555f7f4a8dd9d75/href">https://medium.com/media/406b38c580898bbb3555f7f4a8dd9d75/href</a></iframe><p>Güvenli adres kodumuzun doğru çalışıp çalışmadığını test etmek için oluşturduğumuz form üzerinden next değerini farklı bir adres ile değiştirebilirsiniz.</p><h4>Serializer</h4><p>Serialization(Serileştirme) işlemi elimizdeki sınıf veya nesnelerin saklanmak veya gönderilmek istenen formata dönüştürme işlemidir. Kaydettiğimiz nesne veya sınıfların tiplerini bilemediğimiz durumlarda yeniden kullanılabilirlik açısından serileştirme işlemi yaparak, daha sonrası için kullanılabilirliğini artırabiliriz. Bu işlem verilerimizin küçülmesini ve performans artışını beraberinde getirecektir.</p><p>REST API üzerinde de oynamalar yapmamızı sağlayacak ve serialization işlemimiz için bize yardımcı olacak django kütüphanesi olan djangorestframework’ü pipenv install djangorestframework kodunu konsol ekranına yazarak projemize kuralım. settings.py dosyamızda INSTALLED_APPS dizimize rest_framework ‘ü ekleyip kaydedelim. Artık kodumuzu yazarken bu kütüphaneyi sayfamıza çağırarak kullanabiliriz.</p><p>Aslında serialize işlemimizi book_list içerisinde kitaplarımızı books = [{&#39;id&#39;:x.id, &#39;name&#39;:x.name, &#39;author&#39;:x.author, &#39;description&#39;: x.description} for x in blist] şeklinde tanımlayarak yapmıştık. Bu işlemi ayırarak model içerisine ufak bir ekleme yapıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6810a3c3117c2a17bf68332b618d02/href">https://medium.com/media/4e6810a3c3117c2a17bf68332b618d02/href</a></iframe><p>Model içerisine serialize fonksiyonumuzu tanımladıktan sonra, books_list view’ımızı daha temiz hale getirebiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec661cdab162a26383c3b4feeb2e743/href">https://medium.com/media/2ec661cdab162a26383c3b4feeb2e743/href</a></iframe><p>Artık değişkenimizi tanımlarken yaşadığımız kod karmaşasından kurtulduk.</p><p>Kitap kaydetme işlemini Form kullanarak yapmıştık. Şimdi bu işlemi bir de djangorestframework ile serialization işlemi de yaparak tekrar yazalım. serializer.py adında bir dosya oluşturarak form.py içerisinde yazdığımız kodu buraya uyarlayalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/770098d8ed5e36cead43949fe66aa24e/href">https://medium.com/media/770098d8ed5e36cead43949fe66aa24e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f358cfb9d4d06b3bf49aa1b5c48abd4e/href">https://medium.com/media/f358cfb9d4d06b3bf49aa1b5c48abd4e/href</a></iframe><p>Serializer dosyamızı hazırladık şimdi de view tarafında bunu kullanalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c8b4776e5e37dfc0f3b4dd605a3d6cd/href">https://medium.com/media/8c8b4776e5e37dfc0f3b4dd605a3d6cd/href</a></iframe><p>Daha önce oluşturduğumuz book_create_view fonksiyonumu _pure ekleyerek değiştirdim. Oluşturduğum serializer ile bu fonksiyonu yeniden yazdım. Öncekinde bir html dosyası renderlamıştık. Şimdi ise ekrana dönen sonucumuzu json olarak bastırdık: ki front end tarafından bu fonksiyonu tetiklerken, dönen sonuçları front end tarafında işleyelim.</p><p>Django View’lardan Django Rest Framework View’lara doğru geçiş yapalım.</p><p>Önce book_create_view fonksiyonumuzu değiştirerek başlayalım.</p><p>from rest_framework.response import Response ve from rest_framework.decorators import api_view kodlarını view sayfamıza ekliyoruz ve book_create_view sayfamızın görünümünü API sayfası olarak değiştiriyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3fd62bb39e0e709c3c3011edf964ad1/href">https://medium.com/media/f3fd62bb39e0e709c3c3011edf964ad1/href</a></iframe><p>@api_view() kodunu fonksiyonumuzun üstüne ekleyerek çalışacak fonksiyonun bir API görünümü almasını sağlıyoruz. İçerisine verebileceğimiz, POST-GET gibi parametreler ile bu fonksiyona hangi metodlar ile erişilebileceğini yazıyoruz. Kitap eklerken biz POST metodunu kullandık ve diğerlerini istemiyoruz. Döndüreceğimiz sonuçları da JsonResponse değil Response olarak gönderiyoruz artık.</p><p>Aynı işlemi kitap listeleme fonksiyonumuz olan books_list ve book_detail_view için de yapıyoruz — fonksiyonun üstüne @api_view([&#39;GET&#39;]) ekleyip JsonResponse kodumuzu Response ile değiştiriyoruz.</p><p>Hepsi bu! — değil, elbette. Fakat şuan pratiğe devam edebilmemiz için ihtiyacımız olanları karşıladık. Djangorestframework ile ilgili daha fazla bilgi edinmek için <a href="https://www.django-rest-framework.org/">dökümantasyon</a> sayfasını ziyaret edebilir, kullanabileceğiniz faydalı parametreler hakkında bilgi edinebilirsiniz. Dökümantasyonları çok güzel hazırlanmış.</p><h3>Tests</h3><p>Django tarafında yapacağımız son işlemimiz, test kodumuzu yazmak. TDD(Test Driven Development) tarafımızı en basit aşamadayken besleyip alışkanlık kazanırsak, başka bir dilde bile olsa bu alışkanlık bize fazlasıyla zaman kazandıracaktır.</p><p>Uygulamamızı kurduğumuzda test dosyamızı da beraberinde getiriyor. Komut satırına ./manage.py test books yazdığımızda testimizi çalıştıracak ve ilk çıktımız şu şekilde olacak:</p><pre>System check identified no issues (0 silenced).</pre><pre>----------------------------------------------------------------------<br>Ran 0 tests in 0.000s</pre><pre>OK</pre><p>Sonuçlar mükemmel. Çünkü içeride bir test kodumuz yok. Bu mükemmelliği korumayı umut ederek yolumuza devam ediyoruz. test.py dosyamızın içerisinde Books modelimiz için bir test yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad81dc7ed1ab5fdcb4ca2f6b11a17367/href">https://medium.com/media/ad81dc7ed1ab5fdcb4ca2f6b11a17367/href</a></iframe><p>Bu testte yeni bir kitap ekledik ve testi çalıştırdığımızda yeni bir kullanıcı ekleyip id’sini kontrol edecek. Eğer kaydedemediyse veya kaydettiği veri olması gerekenden farklıysa hata verecek.</p><pre>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.<br>----------------------------------------------------------------------<br>Ran 1 test in 0.003s</pre><pre>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>Test kodumuz hatasız bir şekilde çalıştı. Eğer self.assertEqual(book_obj.id, 5) yapsaydık testimizi çalıştırdığımızda AssertionError: 1 != 5 diye bir hata alacaktık. Bu işlemi yaparken ilk defa veri girişi yapıyor gibi varsayıyor ve ilk girilen verinin 1 olması beklenirken 5 mi diye kontrol ediyoruz. Aynı hata, eğer oluşturulan objenin id’si 1 olmazsa da gelecekti. Dünyanın binbir türlü hali var bir bakmışsın integer değer bile dönmemiz objeden. Bilemezsin, her şey olabilir bu hayatta. Testing konusunda Django’nun <a href="https://docs.djangoproject.com/en/3.0/intro/tutorial05/">dökümantasyonundan</a> faydalı kullanımları görebilirsiniz.</p><p>Peki her şey tamamlandıktan sonra yaptığımız bu işi biz nasıl yayına alacağız? Bu kısımda hemen her servis sağlayıcının dökümantasyon sayfalarında bilgi mevcut. Yorumlanabilir bir tarafı olmadığı için sizlere doğrudan kaynak vereceğim. Django’yu bulut tabanlı bir sistemde çalıştırabilirsiniz. Bunun en popüler örneklerinden birisi <a href="https://devcenter.heroku.com/articles/getting-started-with-python">Heroku</a>. Doğrudan kendi yönergelerini takip ederek ilk projenizi yayına alabilirsiniz. Eğer kendi sunucunuzu kullanmak isterseniz <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04">DigitalOcean </a>sayfasında yayın yönergeleri mevcut. Bu işlemler ssh bağlantısı kurabildiğiniz bütün sunucularda aynı olacaktır.</p><p>Şuana kadar Django ile yapacağımız işlemleri tamamladık. Kitap ekleme, listeleme ve istenilen kitabı ekrana bastırdık. Tekrar eden kodları, yazıyı uzatmamak için eklemedim. Elbette ki her şey bu kadarla bitmiyor. Yazdığımız her satır kodun bir alternatifi mevcut. Her başlık kendi içerisinde daha da derinlere iniyor. En basitler ile yola çıkarak, bol pratik ile kendimizi geliştirmeye devam edeceğiz. Bu yazıda kullandığım kaynak kodlarını <a href="https://github.com/baris5d/DjangoReact">Github </a>üzerinden inceleyebilir, dilerseniz katkıda bulunabilirsiniz.</p><p>Soru veya sorunlarınız için bana <a href="https://twitter.com/baris5d">Twitter </a>üzerinden ulaşabilirsiniz.</p><p>Bu yazının devamı olan, React ile arayüz geliştirmeye giriş yaptığım <a href="https://medium.com/@baris5d/django-ve-react-ile-full-stack-react-d9b84b58df8e">Django ve React ile Full Stack — React</a> yazıma da bekliyorum.</p><p>Happy codding! :)</p><p>Github, Twitter, Instagram : @bari5d</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dcecf7e4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React SEO Problemi (mi?)]]></title>
            <link>https://medium.com/@baris5d/react-seo-problemi-mi-31a91167d1d7?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a91167d1d7</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[crawling]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 13:26:05 GMT</pubDate>
            <atom:updated>2020-06-16T13:26:05.589Z</atom:updated>
            <content:encoded><![CDATA[<p>Başlamadan önce, aslında bu yazı React özelinde olsa da JavaScript ile geliştirilen bütün web yazılımlarında bu sorunun yanağından bir makas mutlaka alacaksınız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*jTB-GxXzGt3ocDJ-SpZVbA@2x.png" /></figure><p>Yaşadığınız soruna öncelikle nedenleri ve başlangıçtan itibaren nasıl bir çözüm ile yaklaşmamız gerektiğini anlatmaya çalışacağım. Bir şekilde işe başladınız ve hızlı çözüme ihtiyacınız var diyelim; onun da cevabını bu yazıda vermeye çalışacağım.</p><h3><strong>Google botları nasıl çalışır?</strong></h3><p>Google 3 adımda sonuçları oluşturur.</p><p><em>Crawling</em></p><p>Bu kısım internetteki sayfaları bulmak ile alakalı. Web sitelerinin saklandığı merkezi bir sistem olmadığı için Google yeni sayfalar için arama yapar ve cevap alabildiklerini bilinen siteler olarak işaretler. Siteye girdikten sonra ise site içerisindeki linkleri keşfederek onları test eder. Site içerisinde bulunan veya bulunmayan diğer linkler için ise sitemap dosyanıza bakar.</p><p>Diğer tarafta ise Google tarafından daha önceden taranmış sitelerde bulunan internet adreslerine de bot göndererek tarama gerçekleştirebilir.</p><p><em>Indexing</em></p><p>Bir sayfa keşfedildikten sonra, o sayfanın ne ile alakalı olduğunu anlamaya çalışır. Site içeriğini analiz ederek fotoğrafları, videoları ayrıştırarak site içeriğini anlamaya çalışır.</p><p>Video ve görselleri bir yazı kadar anlayamayacağı için yüksek oranda sayfa içerisindeki başlık ve içeriklerden anlamaya çalışacaktır.</p><p><em>Serving (and ranking)</em></p><p>Bir kullanıcı Google’da arama yaptığında aratılan sorgu ile ilgili en uygun sonuçları listeler. Indexleme ile yaptığı kategorilemeler sayesinde en iyi sonucu saptamaya çalışır ve ona göre hareket eder.</p><p>Yukarıda basitçe yazdığım başlıklara ait detaylı bilgiler <a href="https://support.google.com/webmasters/answer/70897?hl=en#:~:text=The%20program%20that%20does%20the,%2C%20bot%2C%20or%20spider).&amp;text=As%20Googlebot%20visits%20each%20of,to%20update%20the%20Google%20index.">Google support</a> sayfasında mevcut.</p><p>SEO ile alakalı başlangıçta bilmemiz gerekenler aslında bunlardan ibaret. SEO çalışması adı altında ücretli olarak yaptırılan hizmetler ise Google’ın sayfaları tararken nerelere baktığını ve nerelerden daha net sonuçlar elde edebileceğini bilmekten ibaret. Ortada bir sihirbazlık gösterisi yok yani.</p><p>Peki gelelim esas sorumuza:</p><h4>React ile yapmış olduğum sitem Google’da neden tek sayfa olarak görünüyor?</h4><p>Bu aşamada karşımıza üç tane terim çıkıyor: CSR(Client-Side Rendering) ve SSR(Server-Side Rendering).</p><h4>CSR(Client-Side Rendering)</h4><p>CSR veya Client-side rendering olarak çalışan bir adrese giriş yapıldığında boş bir sayfa döndürür ve JavaScript ile bu sayfa içeriğini doldurur. Adımlar şu şekilde gerçekleşir:</p><p><em>○ Kullanıcı bir istek gönderir (example.com)</em></p><p><em>○ Sunucu veya CDN aracılığıyla HTML, CSS, JavaScript ve diğer statik dosyalar kullanıcıya gönderilir</em></p><p><em>○ Tarayıcı bu dosyaları indirir</em></p><p><em>○ Tarayıcı JS dosyalarını aldıktan sonra içeriği almak için API isteği gönderir ve sonuçları kullanılması istenen şekilde işler</em></p><p><em>○ Son olarak ise oluşan son içerik DOM aracılığıyla kullanıcıya gösterilir.(Botlar tarafından işlenebilir hale gelir)</em></p><h4>SSR(Server-Side Rendering)</h4><p>SSR’da kullanıcı tarafından görüntülenecek olan HTML dosyası sunucu tarafında hazırlanıp kullanıcıya okunabilir halde gönderir. JavaScript kodları çalıştırılmadığı haliyle bile okunabilir bir içeriğe sahiptir. Sayfa yüklendikten sonra JavaScript kodları çalıştırılır ve arayüz kütüphanelerinin sunduğu özellikleri kullanmaya başlar. Bu tipte ise işlemler şu şekilde gerçekleşir:</p><p><em>○ Kullanıcı bir istek gönderir (example.com)</em></p><p><em>○ Sunucu isteği kabul eder ve HTML dosyasının tamamını oluşturur ve gönderir</em></p><p><em>○ Tarayıcı gelen HTML dosyasını ve JavaScript,CSS dosyalarını indirir (Botlar tarafından işlenebilir halde)</em></p><p><em>○ JavaScript ve CSS dosyaları işlenir ve tasarım istenilen hali alır.</em></p><p>Elde ettiğimiz bu bilgiler ışığında ilerlemek gerekirse botlar sayfayı ziyaret ettiğinde neler ile karşılaşacağı hakkında az çok bir fikrimiz var artık. Kısaca CSR sistemde bot siteye geldiğinde ilk olarak boş bir sayfa görür ve JavaScript ile oluşturulan DOM’lardan sonra sayfa okunabilir hale gelir. SSR sistemlerde ise sunucu yanıt verdiğinde sayfa okunabilir halde karşımıza gelir.</p><p>Peki React ile bir site yaptık yayına aldık fakat Google sitemizi indexlememekte ısrarcı(CSR). Öncelikle robots.txt dosyamızı yapılandırmamız lazım ki gelen botlar nereye gideceğini bilsin. Meta tag’leri üzerinde herhangi bir değişiklik yapmadıysak zaten boş bir dosya olarak yüklenen sayfalarımız arasındaki farkı Google göremeyecek; veya hatalı görecektir. Basit ve kullanışlı bir component olan React Helmet’i bu işlem için önerebilirim. Ben elin component’ini kullanmam diyenler için ayrı bir yazıda en baştan bunu nasıl yapabileceğimizi de yazabilirim.</p><p>Eğer React Router kullanıyorsanız sayfa değişimleriniz JavaScript ile gerçekleşeceği için Google onları gerçek bir link gibi görmeyebilir. Bu sebepten bir sitemap hazırlamakta fayda var. Bir modül aracılığıyla bunu gerçekleştirmek isterseniz <a href="https://www.npmjs.com/package/react-router-sitemap">react-router-sitemap</a> önerebilirim. Google Search Console aracılığıyla da sitenizin akıbetini takip edebilirsiniz.</p><p>Arayüz kütüphaneleri ile geliştirdiğiniz siteleriniz için SSR çözümleri de mevcut. Popüler olanlardan örneklendirmem gerekirse;</p><p>React için <a href="https://nextjs.org/">Next.js</a> , <a href="https://www.gatsbyjs.org/">Gatsby</a></p><p>Vue için <a href="https://nuxtjs.org/">Nuxt.js</a></p><p>Angular için <a href="https://angular.io/guide/universal">Angular Universal</a></p><p>Milyonlarca sitenin botlara göre davranmasındansa, botların milyonlarca siteyi kapsayacak şekilde yapılandırılmasını ne kadar istesem de eminim arama motorları da Frontend kütüphanelerini yakından takip ediyordur ve mutlaka bu konuya el atacaklardır diye düşünüyorum.</p><p>Yazıda eksik veya boş kalan yerler olmuş olabilir. Elimden geldiğince kısa tutmaya, sıkmamaya çalıştım. Umarım birilerine faydası olur. Eksik kalan veya merak ettiğiniz yerler için soru sormaktan çekinmeyin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a91167d1d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobilleşme —Twitter’ın yeni tasarımı]]></title>
            <link>https://medium.com/@baris5d/mobille%C5%9Fme-twitter%C4%B1n-yeni-tasar%C4%B1m%C4%B1-9641f27452f2?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9641f27452f2</guid>
            <category><![CDATA[teknoloji]]></category>
            <category><![CDATA[tasarım]]></category>
            <category><![CDATA[sosyal-medya]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Thu, 25 Jul 2019 16:23:09 GMT</pubDate>
            <atom:updated>2019-07-25T16:23:09.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wROSrFz5lcheVJL_JxYCug.jpeg" /></figure><p>Twitter geçtiğimiz günlerde yeni tasarımını resmen yayına aldı. Artık beğenseniz de beğenmeseniz de bu yeni tasarım ile tanışmak ve kaynaşmak zorundasınız.</p><h3>Twitter on Twitter</h3><p>Woah, what&#39;s this? A shiny new https://t.co/q4wnE46fGs for desktop? Yup. IT&#39;S HERE. https://t.co/8y4TMzqBGa</p><p>Twitter’ın yaptığı bu hareketle ‘mobilleşme’ konusunda bir iki kelam etmek istedim.</p><p>Telefonlarımızın birbirinden tatlı hal almaları neticesinde mobil kullanımlar bir hayli arttı. Bilgisayar kullanımları ile eşdeğer hatta zaman zaman telefonların daha fazla kullanıldığı istatistikler ile anlatılmış. Bunları uzun uzun anlatmaya gerek yok diye düşünüyorum, <a href="http://gs.statcounter.com/platform-market-share/desktop-mobile/worldwide/#monthly-201802-201906">statcounter’ın </a>verilerine göre güncel mobil kullanım 52.69% görünmekte.</p><figure><img alt="http://gs.statcounter.com/platform-market-share/desktop-mobile/worldwide/#monthly-201802-201906" src="https://cdn-images-1.medium.com/max/1024/1*t38W2brvBQTXTOCSEN3Vcw.png" /><figcaption>Desktop vs Mobile Market Share Worldwide — June 2019</figcaption></figure><p>İşverenler veya girişimciler artık mobil öncelikli çalışmakta. Mobil uygulama, mobil uyumlu internet siteleri kimi zaman masaüstü tasarımların bile önünde geliyor; görünüşe göre artık mobil çalışmalar masaüstü görünümüne yön vermekte. Bunun başlıca sebebi olarak şirket maliyetini görüyorum. İnsanlar artık bir uygulama ismi veya internet adresi duyduğunda ilk olarak mobil üzerinden ziyarette bulunuyor ve ilk izlenimi orada kazanıyorlar. Hatta 2011 yılında kurulan Connected2.me uygulaması 2018 yılında masaüstü servisini tamamen kapatmış durumda. Mobil/Masaüstü kullanım istatistiklerine göre masaüstü servise sağlamış oldukları hizmet maliyetinin geri dönüş bazında yetersiz olması sebep olmuş olsa gerek.</p><p>Facebook da kullanıcı deneyimi açısından masaüstünde mobil deneyimi izlemişti. Ki bana kalırsa Facebook’un sökülüp baştan takılması gerekmekte çünkü içeride aktif hesaptan çok ölü kod mevcut. Neyse Facebook’a da gerekli yargıyı dağıttığımıza göre konumuzdan daha fazla sapmadan yolumuza devam edelim.</p><p>Twitter çok ufak değişiklikler haricinde uzun zamandır gözle görülür bir değişiklik yapmamıştı. Reklam politikalarını henüz oturtamamış olmalarını da baz alırsak bu yeni tasarım şirket için temiz bir adım olabilir. Çekirdek ürünü geliştirmek ve inşa etmek diğer sosyal medya ağlarına göre sessiz bir dönüm noktası olabilir. Yeni yapılan tasarımda daha önce benim sıkça kullandığım fakat çoğu insanın haberinin bile olmadığı listeler bölümü, direkt mesajlar arasında gezinti gibi bir çok özelliği tek bir listeye koyup gezintiyi kolaylaştırmak istemişler. Twitter mühendisleri masaüstü siteyi mobil üzerinden inceliyor olacaklar ki; yazıları ve ikonları bir hayli büyütmüşler. Kişisel görüşüm olarak bu tercihi hiç beğenmedim.(Sanki diğer yönlerini beğenişim gibi…) Bütün içeriği gözümüze sokarcasına “bak ben de buradayım” nidaları kulağıma geliyor tasarıma bakarken.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26BRGxMMN3Pn1MMdG%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Felection2016-rnc-republican-national-convention-2016-26BRGxMMN3Pn1MMdG&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26BRGxMMN3Pn1MMdG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5e28297ab784bd81b614d3a23c54cf0/href">https://medium.com/media/d5e28297ab784bd81b614d3a23c54cf0/href</a></iframe><p>Yeni tasarımın eskisine nazaran daha hızlı çalıştığını söylemeden geçmeyelim. Gelen söylemlere göre eski site eski bir teknoloji yığınının üzerine inşa edilmiş ve bu sebepten güncellemelerin gelmesi bir hayli uzun sürüyormuş. <a href="https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/buildingthenewtwitter.html">Twitter’dan abilerimizin</a> söylediğine göre yeni tasarımdaki iki hedef şöyleymiş;</p><ol><li>Yeni özellikleri geliştirmeyi daha hızlandırmak ve daha kolay hale getirmek.</li><li>Her kişi ve her cihaza aynı deneyimi sunmak.</li></ol><p>Masaüstü deneyimleri daha çok seven bir insan olarak mobilde iyi deneyimin yaşanmasını isterim fakat masaüstü ile bunları eşlemek hoş ve kullanışlı değil.</p><p><a href="https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/buildingthenewtwitter.html">Twitter</a> üst menünün masaüstü ile aynı olmadığını ve kullanıcıların mobilde kendi isimlerini görüntüleyemediğini, bu sebepten masaüstünde de bu görüntüyü kaldırdıklarını söylüyor. Basit gibi görünen bu eksiklik masaüstünde hoş bir deneyimdi. Masaüstünden bunu kaldırmak yerine mobili buna adapte edebilirlerdi. Kötüyü iyiye çevirmek yerine iyiyi kötüye çevirmişler gibi görmekteyim bunu.</p><p>Arafta kalmış düşüncelerim ile yeni Twitter düzenine alışabilmeyi kendi adıma temenni ediyorum. Yapmış oldukları bu değişiklik, Twitter’ın önümüzdeki zamanlardaki gelişimini olumlu yönde etkileyecek gibi görünmekte. Aktif bir Twitter kullanıcısı olarak yapacakları değişikliklerin özellikle kullanıcı deneyimi açısından daha iyiye gitmesini diliyorum.</p><p>Bu yazıyı aynı zamanda <a href="https://irposts.com/">IRPosts </a>üzerinden okuyabilirsiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9641f27452f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Henüz başaramamış bir insan: Bana söz düşer mi?]]></title>
            <link>https://medium.com/@baris5d/hen%C3%BCz-ba%C5%9Faramam%C4%B1%C5%9F-bir-insan-bana-s%C3%B6z-d%C3%BC%C5%9Fer-mi-4c3ff723ace0?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3ff723ace0</guid>
            <category><![CDATA[programlama]]></category>
            <category><![CDATA[başarı]]></category>
            <category><![CDATA[kişisel-gelişim]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 08:19:13 GMT</pubDate>
            <atom:updated>2018-01-21T08:34:18.689Z</atom:updated>
            <content:encoded><![CDATA[<p>Evet, henüz başaramadım…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRqR4JeqiKu7g7c3KeYthA.png" /><figcaption>Ne bakımdan?</figcaption></figure><p>Öncelikle başarmayı ele alalım. Başarı sizce nedir? Taktir edilmek mi? Büyük paralar kazanmak mı? Şan şöhret sahibi olmak mı?</p><p>Başarı hayatın farklı dönemlerinde farklı şeylerle özdeşleştiriliyor. İlk alfabeyi öğrenişimiz; başarı, üniversite bitene kadar yüksek notlar almamız bir başarı, iş hayatına girip terfiler almamız ve yüksek miktarlarda para kazanmamız bir başarı. Her zaman bunları görüyoruz ve özümsüyoruz. Peki gerçekten başarı bunlardan ibaret mi?</p><p>Yaşam standartlarını belli bir seviyeye getiren insanların bir kısmı inzivaya çekiliyor, bir kısmı ise hayallerini veya aklına o an gelen fikirleri hayata geçiriyor. Sonra biz de onlar gibi olmak istiyoruz. Peki bunların sırasını her zaman herkes aynı düzende mi yaşamalı? Başkalarının başarı hikayelerini dinlemeyi seviyoruz. Bir çoğunda bir not bulunuyor: “Ben yaptım oldu, siz yapınca olacak diye bir şey yok.” Tam olarak böyle yazmasa da bu mesajı veren bir not oluyor.</p><blockquote>Peki biz ne yaparsak yapalım neden kendimizi başarılı hissedemiyoruz?</blockquote><p>Bence bunun sebebi başarıyı tanımlama şeklimiz. Kendi yaşamımdan örnekler vererek ilerlemek istiyorum. <a href="https://medium.com/@baris5d/benim-ad%C4%B1m-bar%C4%B1%C5%9F-boyum-1-10-b938a34f8fd5">İlk yazımda</a> kendimden biraz bahsetmiştim. Ben programlamaya küçük yaşlarda başladım. Benden beklenen şeyleri pek veremediğimi düşünüyorum. Çünkü başarı o yaşlarda yüksek notlardan ibaretti çevremdekiler için. Ama insanların gözden kaçırdığı bir nokta vardı. Ben küçücük yaşıma rağmen programlamayı öğrenmiş ve kendimi geliştirmeye adamıştım. Etrafımdaki insanlar interneti yeni yeni keşfederken, ben onların karşısında kendi ürünlerimi sergiliyordum. Ama bunu kimse başarı olarak görmüyordu. Buralar biraz sitem koktu…</p><p>Yaşıma göre çok iyi işler yaptığımı düşünüyorum. Bunu herhangi bir insan başarı olarak parmakla işaret etmese de bunu kendi içimde bir başarı varsaydım. Ancak yaşım ilerledikçe yerimde saydığımı hissetmeye başladım. Bu bir başarısızlıktı. Cem Yılmaz’ın bir soru cevap videosunda <a href="https://www.youtube.com/watch?v=vfz0ObdaPsY">“Şans mı Emek mi?”</a> sorusuna verdiği cevap tam olarak bu durumuma cevap aslında. İnsanlar uçak sürmeyi öğrenmişken ben arabayı keşfettiğime sevinir halde duruyordum. Yaşım ilerledikçe bilgim eskidi. Bu kısımda birtakım bahaneleri ortaya sürmem gerekiyor sanırım. Ama geçerli saymıyorum bu konuyu ayrıca ele alacağım.</p><p>Sanki 30&#39;unu geçmiş bir birey gibi söylüyorum ama geçen her saatin dolu olması gerektiğini düşünen bir insanım. O yüzden kaybettiğim bir hafta dahi gözüme batıyor. Peki, o kadar başarıyı tanımlamaya çalıştım bu konuyu nereye bağlayacağım? Başarı şudur diyebileceğimiz her şeyi bir kenarı bırakın. Yepyeni başarılar üretin ve onun sahibi siz olun. Ama insanlar eli ayağı tutan, ayakları yere basan ve bir insan gibi hareket edebilen robotlar üretmişken, metalin altına tekerlek bağlayıp hareket ettirdim diye sevinmeyin. Evet sizin için yeni bir şey bunu kendi içinizde bir başarı varsayabilirsiniz. Kendimizi yücelttiğimiz kadar yokuz, ama kabul ettiğimizden fazlasıyız.</p><p>Eğer ki bu yazıyı okuyan akranlarım varsa; evet, kaybımız çok. Çağın çok gerisindeyiz, etrafımızda bir ton problem var. Ama gelecek biziz. Bunlardan yakındığımız kadar çalışmazsak, hiçbir şey değişmeyecek. Evet ben başardım. Karşıma çıkan zorluklar yüzünden pes etmeyerek, başarı kotamı her seferinde ileriye sürerek, yaptıklarımı veya yapamadıklarımı fark ederek ben başardım.</p><p>“Boş tenekeden çok ses gelir” diye bir laf var. Bilenler sustukça bilmeyenler konuşmaya devam edecek. Dolu tenekeler ise tozlu raflarda yok olup gidecek.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c3ff723ace0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benim adım Barış, boyum 1.10]]></title>
            <link>https://medium.com/@baris5d/benim-ad%C4%B1m-bar%C4%B1%C5%9F-boyum-1-10-b938a34f8fd5?source=rss-69f3241c7a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b938a34f8fd5</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[starting]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[autobiography]]></category>
            <dc:creator><![CDATA[Barış Dede]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 01:36:27 GMT</pubDate>
            <atom:updated>2017-11-09T07:57:42.350Z</atom:updated>
            <content:encoded><![CDATA[<p>Yazı yazma konusunda biraz acemiyim. O yüzden yazının başından sonundan kafanıza göre okuyarak doğru düzeni kendiniz bulursunuz diye düşünerek yazıya bodoslama giriyorum.</p><p>Öncelikle kim bu yakışıklı sorusuna cevap verelim:</p><p>7 Temmuz 1996&#39;da Ankara’da dünyaya gözlerini açıp, 2006 yılından itibaren bakışını teknolojiye çevirmiş bir gencim. İlk bilgisayarım alındığı gün Google amcamıza “Fotomontaj programı indir” diyerek düştüm bu yola. Devamında arattığım anahtar kelimeler giderek gelişti, kendimi aştım. İlk programlamaya adımım 5. sınıfta başladı. Öncesinde sürekli olarak bilgisayar terimleri ile ilgili araştırmalar yaptım.</p><p>Forum siteleri oluşturmaya çalışarak hayatımın kayda değer bir parçasını harcadım. Bedava-sitem denilen bataklığa düşerek ilk html parçacıklarını öğrenmeye başladım. Akabinde “free template” kelimesini nereden duyduysam yönümü oraya çevirip hazır temalar indirerek onları incelemeye adadım kendimi. Bana tüyolar verecek, yol gösterecek insanlara pek ulaşabildiğim söylenemez. O yüzden kaynak kodu okuyup tekrar etme sürecim bir hayli uzadı. O dönemde kullanabileceğim editörleri pek araştırmamıştım, Adobe Dreamweaver ile kendimi kör etmekle meşguldüm. Yanlış hatırlamıyorsam kayda değer bir tasarımı çıkarmam 6. sınıf sonlarında olmuştu. Sonrasında girdiğim internet sitelerinde yazılar ekleme, çıkarma gibi şeylerin olduğu dikkatimi çekti. Bunları nasıl yapabileceğimi araştırırken ASP ile karşılaştım. Şimdiki ASP.NET felan değil, kemiksiz ASP.</p><p>Beni kodlamadan soğutan bir dönem yaşadım. ASP’yi hatırlayanlarınız vardır, öyle tertip düzen pek de yoktu. Vel hasıl kelam, 8. sınıfta “bizim kuzen de internet siteleri yapıyor” olarak önerildiğim kişi nasıl güvendiyse bana ilk işimi verdi. Hayatımda kazandığım en zor paraydı. ASP’yi pratiğe döktüğüm ilk ve tek iş oldu. Alnımın akıyla işimi teslim ettim, paramı alıp eve koştum. Sanki dünyada hiç kimse (miktar söylemem yanlış olmaz umarım) 450 milyon lira kazanmamış gibi. Öyle zenginim yani siz anlayın. Şuan 450 lira diyoruz ama milyon daha cazip. Para kazanmaya başladığım ilk andan itibaren bu işi devam ettirebileceğimi gördüm. “Ben bir iş yaptım, para etti” cümlesi ile birebir uyuşuyor. Şimdi etrafta para kazanıp iş yapanlar çoğaldı. Neyse sitemimizi başka bir yazıda ederiz.</p><p>Liseye 1&#39;deyken bir sürü statik site yaptım. Neden? Çünkü ASP’yi sevmedim, insanları da statik siteye ikna ediyordum. Bunun bir hal çaresine bakmam gerekiyordu. Php dilini duyduktan sonra bol bol araştırdım. O zamanlarda Front End, Back End terimleri yoktu. Herkes Full Stack Developer. Lisede yaz stajında bana php ile ilgili güzel bir başlangıç yolu açıldı. Ben de aldım hızımı ve hızlı bir şekilde olayı kavradım.</p><p>Yaptığım işin, yazdığım kodun ne anlam ifade ettiğini lise 2 civarında anlamaya başlamıştım. Ben birşeyler yazıyorum, istediğim şekilde çalışıyor ama işin kemiğinde ne var fikrim yoktu. Kütüphaneler, diller gibi şeyleri hiç ayırt etme bile yoktu. Bir kod yazıyorum tablo oluşuyor, bir kaç kodla destekliyorum renkleniyor şekilleniyor. Tıklıyorum mailler geliyor felan ama ben ne yapıyorum? Bu saatten sonra yaşadığım gelişme önceki hiç ettiğim seneler için içimin cız etmesini sağladı. Çok yavaş ilerlemiştim. MySQL, PHP, CSS, Javascript, C#, ASP dillerini kullanmıştım ama kıymetleri ve gelecekleri hakkında fikir sahibi değildim. Bir yerlerden kütüphaneler indiriyorum(GitHub) ama içlerini hiç açmıyorum, nasıl istendiyse o şekilde entegre edip kulllanıyordum, sorularımı sorup cevaplar alıyordum(Stackoverflow) ama içerdekiler hakkında birşey merak etmiyordum gibi gibi olaylar silsilesi.</p><p>Ne bildiğimi farketmediğim dönemlerde bile birçok yerde işler yaptım hizmetler verdim. Ucuza gitmişim, bol bol yolmuş insanlar beni. Her geçen gün sorumluluklarım arttıkça öğrendiklerim arttıkça kendimi geri kalıyormuş gibi hissetmeye başladım. Zaman daha da ilerledikçe kendimi sorumlulukları fazla olan birisi sandığım dönemler için “ulan hiç de dolu değilmişim zamanım varmış” gibi sohbetler sürdürdüm, sürdürüyorum kendi içimde.</p><p>Yazı çok uzadı, daha anlatacak çok şeyimiz var o yüzden hızlı bir şekilde toparlayıp kalan konuları da parçalar halinde paylaşacağım.</p><p>Şuan sene 2017, 21 yaşında birşeyler için tırmalayan bir gencim. Php, html, css dillerinde harikalar yarattığını sanan, Java biliyorum diye geçinen, bildiğim en ufak şeyi bile paylaşmalıyım düşüncesinde olup tek bir yazı dahi paylaşmamış bir insanım. GitHub hesabım sahibinden tertemiz duruyor. Yazabileceğim makalelerin, paylaşabileceğim kütüphanelerin basit olduğunu düşünüp kendi içine kapanmış açık kaynak geliştiricisi bir insanım. İronim fazla, aza indirgemeye çalışıyorum. Yaşım kaç olursa olsun, ben;</p><blockquote>“Gelişmekte olan geliştirici genç”</blockquote><p>olarak kalacağım.</p><p>İlk defa bir yazı paylaşıyorum, hatalarımın ve kronolojik sıralama yapamadığım gibi şeylerin farkındayım. Onun dışında bence güzel bir yol açıldı. Bana “Merhaba” deyin, sizi şaşırtayım. Görüşmek üzere…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b938a34f8fd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>