Django Getting File Upload Path for Foreign Keyed
Django provides congenital-in facilities of ForeignKey, ManytoManyField for associating one model to other model. To associate a user model to a post model, one can use various options. This article revolves effectually how to associate a user to its mail service (mail service model). This tutorial uses the concept of foreign keys in Django and at the end, one will be able to create application of postal service upload and likewise contour app which contains all the by uploads of the user.
Prerequisites –
- Cosmos of Django project
- Cosmos of application which can register login and logout the user
- Make migrations in awarding and add database
We accept already created a user application for registration and so we will create a new app that tin can be named every bit userblog (blog upload from the user) .To exercise this create an app in chief project file by writing this lawmaking in your PowerShell or terminal
django-admin startapp userblog
Now this application is bachelor in your projection file and you lot should start add together this awarding to settings.py file in the project and add together this application to INSTALLED_APPS
Now make migrations in your projection and add this application to your project
python manage.py makemigrations python manage.py migrate
Now we accept to use models in this application so that Django tin can create a tabular array for the information which nosotros are going to store in our database and the user can input the information. Nosotros take to create a class in the models.py file of userblog application which is named as Snippet. We will use a ForeignKey class which will hold the id value of the user and information technology holds one to many relationship and so you lot can utilize this class to associate the user to whatever other activities where there is user involvement.
from django.db import models
from django.conf import settings
User = settings.AUTH_USER_MODEL
grade Snippet(models.Model):
user = models.ForeignKey(User,
default = 1 ,
null = True ,
on_delete = models.SET_NULL
)
blogname = models.CharField(max_length = 100 )
blogauth = models.CharField(max_length = 100 )
blogdes = models.TextField(max_length = 400 )
img = models.ImageField(upload_to = 'pics' )
def __str__( self ):
return self .blogname
Besides create a python file named as forms.py and create a ModelForm for the aforementioned to input data from user.
from django import forms
from .models import Snippet
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = [ 'blogname' ,
'img' ,
'blogauth' ,
'blogdes'
]
Nosotros demand to migrate the grade model of Snippet so that Django assistants creates a database for the post upload and details then makemigrations of the grade Snippet and you will see this in django assistants –
Here User is a foreign fundamental which will bear witness all the users and it will store the key number of last example of postal service upload past a user by default it is set to superuser
Now we volition go to views.py file of application and add together the chief code which will be storing the data in database using model form object.
- usblog – This will display all the posts in our homepage
- snippet_detail – This will get the data from the user in the form ad information technology will associate blog to user
from django.shortcuts import render
from django.http import HttpResponse
from .forms import SnippetForm
from .models import Snippet
from django.contrib import letters
def usblog(request):
snipps = Snippet.objects. all ()
render return(asking, 'indexg.html' , { 'snipps' : snipps})
def snippet_detail(request):
form = SnippetForm(request.Post or None , asking.FILES or None )
if asking.method = = 'POST' :
if form.is_valid():
obj = form.save(commit = Fake )
obj.user = request.user;
obj.salve()
course = SnippetForm()
messages.success(asking, "Successfully created" )
return return(asking, 'form.html' , { 'form' :form})
So past now the Django administration has created the database of Snippet class and you can see information technology by visiting Django administration. Now we have to create a simple form.html file which we will comprise a class from where user can enter the queries which nosotros have stated in the form. Here comes the beauty of Django that since we have used model forms for our application Django has created HTML lawmaking of grade which volition have all those queries which we needed. So simply create an HTML file in your templates file(form.html).
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=i.0" >
< meta http-equiv = "X-UA-Uniform" content = "ie=edge" >
< title >Your Blog</ title >
</ caput >
< body >
< form method = "post" enctype = "multipart/form-data" >
{% csrf_token %}
{{form.as_p}}
< button type = "submit" >Submit</ button >
</ form >
</ body >
</ html >
At present nosotros will need a homepage where we will see all the posts of the users then create some other HTML file indexg.html and import the objects of office which we have created in views.py file. (Placed epitome of only trunk part of html to bear witness the python code you can make your ain indexg with features )
< body >
< h1 >Post play< h4 >Only for geeks</ h4 >
</ h1 >
< div form = "topnav" >
{% if user.is_authenticated %}
< a href = "#" >Hi {{user.username}}</ a >
< a href = "accounts/logout" >Logout</ a >
< a href = "snippet_detail" >Write post</ a >
{% else %}
< a href = "accounts/register" >Register</ a >
< a href = "accounts/login" >Login</ a >
{% endif %}
</ div >
< p >
{% for snips in snipps %}
< img src = "{{snips.img.url}}" alt = "Image" class = "img-fluid" >
< h2 class = "font-size-regular" >< a href = "#" >{{snips.blogname}}</ a ></ h2 >
< h3 >{{snips.user}}</ h3 >
{% if user.is_authenticated %}
< p >{{snips.blogdes}}</ p >
{% else %}
< p >Register/Login to know more</ p >
{% endif %}
{% endfor %}
</ p >
</ div >
</ body >
Permit the states become to our chief urls file where we will take an account app and now brand the userblog application as default and add the URLs of your application. Likewise in your userblog application add urls.py and add the links of 2 functions which are form.html and homepage(indexg.html).
Main Urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path(' ', include(' userblog.urls')),
path( 'admin/' , admin.site.urls),
path( 'accounts/' , include( 'accounts.urls' ))
]
userblog urls –
from django.urls import path
from . import views
urlpatterns = [
path( "snippet_detail" , views.snippet_detail),
path(' ', views.usblog, name =' usblog')
]
Start the awarding and register the user to your application and make a postal service
python manage.py runserver
Your browser does not support playing video
GITHUB LINK – Github Repo
Source: https://www.geeksforgeeks.org/associate-user-to-its-upload-post-in-django/
0 Response to "Django Getting File Upload Path for Foreign Keyed"
Post a Comment