These are chat archives for django/django

7th
Dec 2017
MilanRgm
@MilanRgm
Dec 07 2017 02:24
@craiglabenz yes when I remove the trailing slash, it gives me the expected result
:]
@elcolie
Dec 07 2017 02:44
@LukeVideo I don't understand you question. Looks like you need t opost it at stackoverflow
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:22
The file when downloaded is renameed. for example : Capture_décran_de_2017-12-05_17-34-36.png
So my guess is that the problem is the apostrophe ' . I better check the name of the file before download....
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:35
I Know ! @elcolie The problem is i call a read function on the file but it is renamed. Upload is fine but file might be renamed. And then i
def getSha(document):
    ###
    BLOCKSIZE = 65536
    hasher = hashlib.sha256()
    with  open(document, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)
    doc_hash = hasher.hexdigest()
    return doc_hash
only document is document = request.FILES['doc']
:]
@elcolie
Dec 07 2017 10:35
You need to use Django storage engine or something do a temporary.
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:36
wich is the name in the form field.... But not the files name when ' are erased and space replace.
:]
@elcolie
Dec 07 2017 10:36
If you read the file the head of the file to seek to the last and file will be ended.
Why you have to rename a file by yourself?
Django do it automatically already
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:37
           document = request.FILES['doc']
            document_path_str = document_path(request.FILES, request.FILES['doc'] )
            document_hash = getSha(settings.MEDIA_ROOT + "/" + document_path_str)``
I don't do it. But if file not renamed finction find file
:]
@elcolie
Dec 07 2017 10:38
I don't understand
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:38
else file "name with spaces.txt" doesn't exist because django handled it and it it now "name_with_spaces.txt"
so "name with spaces.txt" != "name_with_spaces.txt"
I need to find a way to get the name of the renamed file not the name of submited file. Because if file alredy exist it also is renamed with suffix like test_file_BmATLAM.txt
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:46
So i have a bigger problem than i thought. If two user upload a file called myfile.txt that are different my app would return twice the same hash because the app passes the name from the form BUT on the server there would be two files myfile.txt and myfileJOksUO.txt ... So i have to change the way i call the getSha function. Because the myfileJOksUO.txt would never be passed to the function. Only the one that corresponds to name of the file in the form "myfile.txt" and would always find the first file.
I verified, and if i rename the file with spaces on the server again it works.
So NOW my question is how do i get a reference to the renamed file on the server.
Luke-VideoLibre
@LukeVideo
Dec 07 2017 10:52
I want to upload "stupid file's name.txt" let django rename it on the server to "stupid_files_nameFG86jc.txt" and be able to reference to the file on the server by it's new name.

I musn't use

document = request.FILES['doc']

It isn't pointing to the saved file... Only the name from the form.

:]
@elcolie
Dec 07 2017 11:05
No need to do that.
You are going to the wrong way
Your requirements are
  1. Multiple user upload the identical files to Django
  2. Individual user must be able to query and see his own file only
    Just that?
Luke-VideoLibre
@LukeVideo
Dec 07 2017 11:07
No 2 the views.py return a hash of the file so it needs to find the find it on the server?
Should i use the url of the file? or can i fetsh it in MEDIA_ROOT ?
:]
@elcolie
Dec 07 2017 11:10
I would add hash to the field with UUID4()
class MyFile(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileFiled(upload_to='./upload_files')
    hash = models.CharField()

    //Override the save method to add hashing value
    def save(... ):
            hash = hash_function(self.name)
            return super().save(...)
You can read from the model here.
Luke-VideoLibre
@LukeVideo
Dec 07 2017 11:12
Oh ! In the model !!!
But i wont a hash of the actual file not the name. I have to check that out. I need to pass that kind of function
def getSha(document):

    BLOCKSIZE = 65536
    hasher = hashlib.sha256()
    with  open(document, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)
    doc_hash = hasher.hexdigest()
    return doc_hash
:]
@elcolie
Dec 07 2017 11:15
self.file is a file instance.
Just replace self.name to self.file
Luke-VideoLibre
@LukeVideo
Dec 07 2017 11:15
Hooray ! @elcolie you made my day !
That's what i was looking for XD
:]
@elcolie
Dec 07 2017 11:15
Do you know ReactJS? I need some one guide me on Authentication
Luke-VideoLibre
@LukeVideo
Dec 07 2017 11:16
I don't think i know enough to help anyone...
:]
@elcolie
Dec 07 2017 11:17
That's ok. Glad I can help.
Luke-VideoLibre
@LukeVideo
Dec 07 2017 11:19
That's why you use rest api's :smile: I would love to do more react. but first understand django...
Gauti
@gautamkumar94
Dec 07 2017 12:53
i have an error in djaon rest app . can i ask it here

I have created models and related seriaizers, viewset, filter and added a url path also
``` class NakashtraWork(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='nakshatra_work')
year = models.CharField(max_length=4, blank=False)
nakashtra_month = models.CharField(max_length=15, blank=False)
nakashtra_work = models.TextField(blank=False)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True, editable=False)"
class NakshatraWorkSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
updated = serializers.DateTimeField(read_only=True)
created = serializers.DateTimeField(read_only=True)
created_by = UserSerializer(read_only=True)

class Meta:
    model = NakashtraWork
    fields = ('id', 'user', 'year', 'nakashtra_work', 'nakashtra_month', 'u

class NakshatraWorkViewSet(viewsets.ModelViewSet):
"""
Works
"""
permission_classes = (IsAuthenticated,)
queryset = NakashtraWork.objects.all
serializer_class = NakshatraWorkSerializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
filter_class = NakshatraWorkFilter

def get_serializer_class(self):
    return NakshatraWorkSerializer

def filter_queryset(self, queryset):
    queryset = super(NakshatraWorkViewSet, self).filter_queryset(queryset)
    return queryset.order_by('-id')

def perform_create(self, serializer):
    serializer.save(created_by=self.request.user)

class NakshatraWorkFilter(django_filters.rest_framework.FilterSet):
created = django_filters.DateFromToRangeFilter()
updated = django_filters.DateFromToRangeFilter()
date = django_filters.DateFromToRangeFilter()

class Meta:
    model = NakashtraWork
    fields = ['id', 'user', 'year', 'nakashtra_work', 'nakashtra_month', 'updated', 'created'] ```

and in urls.py router.register(r'work', views.NakshatraWorkViewSet)
but I am not able to do makemigrations
error I get is : File "F:\supernova\supernova_service\supernova_app\urls.py", line 11, in <module>
router.register(r'work', views.NakshatraWorkViewSet)
File "F:\supernova\env\lib\site-packages\rest_framework\routers.py", line 72, in register
base_name = self.get_default_base_name(viewset)
File "F:\supernova\env\lib\site-packages\rest_framework\routers.py", line 152, in get_default_base_name
return queryset.model._meta.object_name.lower()
AttributeError: 'function' object has no attribute 'model'

Luke-VideoLibre
@LukeVideo
Dec 07 2017 12:58
If it's a Class shouldn't it be in the url .asview()
Gauti
@gautamkumar94
Dec 07 2017 13:00
plese help
i am using router
router = DefaultRouter()
router.register(r'work', views.NakshatraWorkViewSet)
urlpatterns = [
    url(r'^', include(router.urls)),]
Luke-VideoLibre
@LukeVideo
Dec 07 2017 13:04
did you try views.NakshatraWorkViewSet.asView()
Because it's a class i think you might want to add this in order to make it work. Not 100% sure but that's what i did Two days ago for a class view that was failing.
Gauti
@gautamkumar94
Dec 07 2017 13:07
@LukeVideo File "F:\supernova\supernova_service\supernova_app\urls.py", line 11, in <module>
router.register(r'work', views.NakshatraWorkViewSet.asView())
AttributeError: type object 'NakshatraWorkViewSet' has no attribute 'asView'
this is the error i am getting
Luke-VideoLibre
@LukeVideo
Dec 07 2017 13:08
sorry ... .as_view() :)
Gauti
@gautamkumar94
Dec 07 2017 13:11
http://www.django-rest-framework.org/api-guide/routers/ as per drf document router = DefaultRouter() router.register(r'work', views.NakshatraWorkViewSet) urlpatterns = [ url(r'^', include(router.urls)),]
its right
Gauti
@gautamkumar94
Dec 07 2017 13:16
TypeError: The actions argument must be provided when calling .as_view() on a ViewSet. For example .as_view({'get': 'list'})
@LukeVideo
Luke-VideoLibre
@LukeVideo
Dec 07 2017 13:17
Sorry i'm not that familiar with DRF...
Gauti
@gautamkumar94
Dec 07 2017 13:31
okk
JsonPipe
@JsonPipe
Dec 07 2017 16:48

When using CreateView do I have to overwrite it with a custom form using form_class in order to successfully upload/save and image?

I can't figure out why I'm getting this:

Exception Type:     TypeError
Exception Value:     expected str, bytes or os.PathLike object, not tuple

The whole thing is barebones, right out of stock.

models.py

class Post(models.Model):
    cover_image = models.ImageField('hero image', upload_to='buildings/', blank=True, null=True)

    def get_absolute_url(self):
        return reverse('details', args=[str(self.slug)])

views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['cover_image']

news/templates/news/post_form.py

  <form enctype="multipart/form-data" method="post" action="">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save"/>
  </form>

Can anyone help me understand?

Felipe Campelo
@fccampelo
Dec 07 2017 18:26
hello
i have a problme
''' TypeError: include() got an unexpected keyword argument 'app_name' '''

``` from django.conf.urls import url, include
from django.contrib import admin

from core import views

app_name = "catalog"

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contato/$', views.contact, name='contact'),
url(r'^produto/$', views.product, name='product'),
url(r'^produtos/', include('catalog.urls', app_name="catalog")),
url(r'^admin/', admin.site.urls),
]

```

this is my code

``` from django.conf.urls import url, include
from django.contrib import admin

from core import views

app_name = "catalog"

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contato/$', views.contact, name='contact'),
url(r'^produto/$', views.product, name='product'),
url(r'^produtos/', include('catalog.urls', app_name="catalog")),
url(r'^admin/', admin.site.urls),
]
```

someone can help me ?
Gauti
@gautamkumar94
Dec 07 2017 18:28
wait
Felipe Campelo
@fccampelo
Dec 07 2017 18:32
File "/home/felipecampelo/Documentos/python/udemy/env/ecommerce/ecommerce/urls.py", line 27, in <module> url(r'^produtos/', include('catalog.urls', namespace="catalog")), File "/home/felipecampelo/Documentos/python/udemy/env/lib/python3.6/site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
this error