I am got stuck to read data from text file which I want to insert into database.
here's my models.py file ..the text file is saved in static folder.
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT=os.path.join(BASE_DIR,'static_cdn')
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py:
from django.db import models
import os
from django.conf import settings
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=100)
author=models.CharField(max_length=20,blank=True)
#classmethod
def create(cls, title,author):
obj = cls(title=title,author=author)
# do something with the book
return obj
file=open(os.path.join(settings.BASE_DIR,'/static/product.txt','r'))
line=file.readline()
for lines in line:
split_line=lines.split("|")
a=split_line[0]
b=split_line[1]
obj=Book.create(a,b)
obj.save()
please help me ..thanks in advance
You are missing a ) after the '/static/product.txt', so the overall address will be:
<BASE_DIR>/static/product.txt/r
(the os.path.join accept any number of arguments)
Simply change it as:
file = open(os.path.join(settings.BASE_DIR,'static/product.txt'), 'r')
It should work if your file is located at <BASE_DIR>/static/product.txt
Related
I want to download a file from the file field through Django views. I tried al lot but didn't get it. Now if I click on the media link it will show in the browser and I want to download it.
Thanks in advance.
models.py
class Question(models.Model):
title = models.CharField(max_length=254)
file = models.FileField(upload_to='exam/question')
def __str__(self):
return self.title
add your Folder path in setting.py file
Consider my folder name is media and that avaliable in where manage.py file is avaliable.
Add path in MEDIA_ROOT
settings.py
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
add MEDIA_URL in appname>urls.py if you are access file from app.
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
#Add Your Path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Download File
For localhost
http://localhost:8000/media/media/filename
in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'pictures')
MEDIA_URL = '/pictures/'
in models.py
class Campaign(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
# this is many to one relationship, on_deleting user, profile will also be deleted
campaign_title = models.CharField(max_length=200, blank=True)
campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures")
in views.py
def landing_page(request):
campaigns = Campaign.objects.all().order_by('-id')
print(campaigns)
return render(request, 'core/landing_page.html',{'campaigns':campaigns})
in landing_page.html
{% for campaign in campaigns %}
<img src="{{campaign.campaign_image.url}}">
{% endfor %}
issue
if file name is abc xyz.jpg, it gets saved into /pictures/campaign_pictures as abc_xyz.jpg
in html template, the src of image should be '/pictures/campaign_pictures/abc_xyz.jpg' but it shows only '/pictures/abc%20xyz.jpg'
I think you missed in urls.py file
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Also correct it with
campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures/")
You can define the 'upload_to' as a callable function and use the os.path to join the directory name with the media url.
Your field will call a function which will provide the path.
campaign_image = models.ImageField(default="default_campaign.png",upload_to=get_campaign_path)
and define your function like this
import os
def get_campaign_path(instance, filename):
return os.path.join('campaign_pictures/',filename)
Reference:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.FileField.upload_to
I have my images downloaded inside the subroot images in my media folder and I'm trying to generate new models which will contain the photo inside the images folder. This is what my model and my view look like:
class Post(models.Model):
...
image = models.ImageField(upload_to="images", blank=True, null=True)
def generate_posts(request):
for i in range(20):
title_ = f'title{i}'
body_ = f'text for post number : {i}'
author_ = f'author{i}'
network_ = randomize_social()
post = Post(title=title_, body=body_, author=author_, social_network=network_)
if randomize_picture():
post.image.save("logo.png", File("images/svante.jpg"), save=True)
else:
post.image = None
post.save()
areGenerated = True
return render(request, "posts/generate_posts.html", {'areGenerated':areGenerated})
The logo.png file is created inside the images folder, but it's blank, 0kb size and when I follow the /generateposts url, I receive this error message:
AttributeError at /generateposts
'str' object has no attribute 'read'
What can I do to solve this problem?
Did you make changes to your settings file? you need to make changes such as
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and don't forget to add these to your urls:
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am facing problem in returned image url, which is not proper.
My return image url is "http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"
But i need
"http://127.0.0.1:8000/media/Capture1.PNG"
When i click on image_url then image open in new browser tab
But currently its shown error:
view.py
from showimage.models import ShowImage
from showimage.serializers import ShowImageSerializer
from rest_framework import generics
# Create your views here.
class ShowImageList(generics.ListCreateAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to=settings.MEDIA)
serializer.py
from rest_framework import serializers
from showimage.models import ShowImage
class ShowImageSerializer (serializers.ModelSerializer):
class Meta:
model = ShowImage
fields = ('id', 'image_name', 'image_url')
settings.py
MEDIA=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
I am new in python and also in django-rest-framework.
Please also tell me how we extend models or serialize class
You might want to try this in your settings:
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your models:
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG"
Finally, i solve this road block with the help of
#Remi
Thanks #Remi
But some other change i do so that i elaborate solution and fix this issue.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads.
try this
image_url = models.ImageField(upload_to='Dir_name')
Dir_name will create when you'll run script.
I am making a Django Project, A Business Directory.
Here I have used ABSOULATE PATHS for Template rendering,
I thnk this might create problem in future.
Please look into my codes and Suggest me how to solve this problem so that it does not create any problem in future.
Please help
my models.py is::
from django.db import models
class Directory(models.Model):
Bussiness_name = models.CharField(max_length=300)
Description = models.CharField(max_length=900)
Number = models.CharField(max_length=100)
Web_url = models.CharField(max_length=800)
Catogory = models.CharField(max_length=200)
def __unicode__(self):
return self.Bussiness_name
class Adress(models.Model):
directory = models.ForeignKey(Directory)
adress_name = models.CharField(max_length=300)
def __unicode__(self):
return self.adress_name
class Photos(models.Model):
directory = models.ForeignKey(Directory)
Photo_path = models.CharField(max_length=100)
Photo_name = models.CharField(max_length=100)
def __unicode__(self):
return self.Photo_name
My view.py is ::
# Create your views here.
from django.http import HttpResponse
from crawlerapp.models import Directory
from crawlerapp.models import Adress
from crawlerapp.models import Photos
from django.template import Context, loader
from django.shortcuts import render
def index(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/index.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def contactus(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/contactus.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def search(request):
if 'what' in request.GET and request.GET['what']:
what = request.GET['what']
crawlerapp = Directory.objects.filter(Catogory__icontains=what)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': what})
elif 'who' in request.GET and request.GET['who']:
who = request.GET['who']
crawlerapp = Directory.objects.filter(Bussiness_name__icontains=who)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': who})
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
And my urls.py is::
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'crawler.views.home', name='home'),
# url(r'^crawler/', include('crawler.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^crawlerapp/$', 'crawlerapp.views.index'),
url(r'^crawlerapp/contactus/$', 'crawlerapp.views.contactus'),
url(r'^crawlerapp/search/$', 'crawlerapp.views.search'),
)
I have 3 html pages INDEX, CONTACTUS, and SEARCH.
Please suggest an alternative of Absolute path so that it create no errors if I someone else clones it from GITHUB and try to run it.
Please help to solve this.
You should list you're template directories in your setting.py files, in the TEMPLATE_DIRS list.
Whether you do that or not, you should dynamically generate the absolute path by using the os.path module's function.
os.path.abspath(__file__)
will return the absolute path to the file it's called in.
os.path.dirname('some/path')
will return the path to the last directory in 'some/Path'
By combining them you can get absolute pathes which will remain accurate on different systems, eg
os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
will return an absolute path to the directory one level above the one containing the current file.
Go read the docs for the os.path module. You'll probably need to use os.path.join as well.
Have you considered reading the Django tutorial?.
Don't forget to set TEMPLATE_DIRS in your settings.py file, a good tip for doing so can be found on another answer; Django template Path
In your project settings.py file:
Add this at the top
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Then to set template path do this:
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "templates"),
)
With this you going to be in the obligation in a future to recheck your all files to change the path in case if you change directories so: in you settings.py file define:
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),
'/path/to/my/project/'
'/path/to/my/project/template/', # for the apps
)
Where templates/ is the directory for your templates.