Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a search webpage for mongoDB database?
I have a mongoDB database of products. And I want to build a webpage in which I can search and filter results from the database. Like this one: https://demo.getsaleor.com/products/category/groceries-5/ (just this page and not the whole website) Any idea how to do this in a simple way? Is Django good for this? Thank You. -
How to add Adsense in Django web app
Guys I have been trying to add Ads on my website This is my Models.py from __future__ import unicode_literals from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Adsense(models.Model): ads = RichTextField() def __unicode__(self): return self.ads This is my views.py from django.shortcuts import render from . import models from models import Adsense # Create your views here. def Ads(request): context = locals() template = "index.html" return render(request,template,context) This is my urls.py from adsense import views as adsense_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.BlogIndex.as_view(), name='home'), url(r'^$', adsense_views.Ads, name='home'), ] This is my index.html ONLY THE body <div id="ad_frame" class="container col-lg-2 " > <p>{{ads|safe}}</p> <h1>ads</h1> </div> -
cant send message with facebook graph api
in my django project i have this function: def mesaj_yolla(): fbid="my_facebook_id" post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<my_access_token>' response_msg = json.dumps({"recipient":{"user_id":fbid}, "message":{"text":"hello"}}) status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg) print(status) it returns: <Response [400]> what is wrong with these codes? i just want to send a message to user. -
Django app with uwsgi, nginx: "no module called site"
I am setting up a django application using nginx, uwsgi, and a virtual environment. I am using python version 2.7.12 and ubuntu 16.04. When I visit my server's IP address, I get the nginx welcome page. However, when I visit my website's domain name I get a 502 bad gateway error. I am following the steps from DigitalOcean's guide. Here is the output from sudo systemctl status uwsgi: β uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-06-24 05:06:46 UTC; 7min ago Process: 11650 ExecStartPre=/bin/bash -c mkdir -p /run/uwsgi; chown django:www-data /run/uwsgi (code=exited, status=0/SUCCESS) Main PID: 11655 (uwsgi) Status: "The Emperor is governing 0 vassals" CGroup: /system.slice/uwsgi.service ββ11655 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Jun 24 05:13:56 localhost uwsgi[11655]: lock engine: pthread robust mutexes Jun 24 05:13:56 localhost uwsgi[11655]: thunder lock: disabled (you can enable it with --thunder-lock) Jun 24 05:13:56 localhost uwsgi[11655]: uwsgi socket 0 bound to UNIX address /home/django/firstsite/firstsite.sock fd 3 Jun 24 05:13:56 localhost uwsgi[11655]: setuid() to 1000 Jun 24 05:13:56 localhost uwsgi[11655]: Python version: 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] Jun 24 05:13:56 localhost uwsgi[11655]: Set PythonHome to /home/django/Env/firstsite Jun 24 05:13:56 localhost uwsgi[11655]: ImportError: No module β¦ -
How to modify fields in Django?
I have been searching for a while a way to make own custom fields. I am interested in making field Like ImageField, which has own properties like url or path. How to write this kind custom field, and can we store any type of data, or it only must be string and integer? -
How set setting environment with DJANGO_SETTINGS_MODULE
I am new in Python Django and i have some question about settings environment. I use git for edit my project and on server i have prod project. But when i edit project on local machine i have my own settings(DATABASE) so if i pull edited proj on server i nedd to change my settings, so i want to set DJANGO_SETTINGS_MODULE, but i dont know what path i must set and where i must allocate my default setting. This is my hierarchy: wow βββ core β βββ admin.py β βββ api_views.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ 0001_initial.py β β βββ __init__.py β β βββ __pycache__ β βββ models.py β βββ __pycache__ β β βββ admin.cpython-35.pyc β β βββ api_views.cpython-35.pyc β β βββ __init__.cpython-35.pyc β β βββ models.cpython-35.pyc β β βββ sitemap.cpython-35.pyc β β βββ urls.cpython-35.pyc β β βββ views.cpython-35.pyc β βββ sitemap.py β βββ tests.py β βββ urls.py β βββ views.py βββ manage.py βββ media β βββ core β βββ iUcZCekdW68_FrqsEHv.jpg β βββ iUcZCekdW68.jpg β βββ qWI5I5NuIeg.jpg β βββ server1.png β βββ server2.png βββ not_found β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β β β¦ -
Deploying Django Project with apache2
Someone can help me why it doesn't work? (my project name is ikh) i'm using ubuntu 16.04 LTS, Apache2 , Python3 ServerAdmin webmaster@localhost DocumentRoot /var/www/ikh WSGIDaemonProcess ikh python-path=/var/www/ikh/ python-home=/var/www/ikh/.env WSGIProcessGroup ikh WSGIScriptAlias / /var/www/ikh/ikh/wsgi.py <Directory /var/www/ikh/ikh> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined -
django model create causes IntegrityError 1062
I have a simple model, and when I use objects.create I am getting IntegrityError (1062, "Duplicate entry '96119' for key 'PRIMARY'"). I searched similar issues, but my case does not have any unique field, nor trying to manipulate the ID field.. The create command is simple: TimelineQuestion.objects.create(alg_type=alg_str, alg_score=0, snippet=rep, child=self) What am I doing wrong? I can reproduce easily, so it is not DB related. Here is the model: class TimelineQuestion(CommonInfo): alg_type = models.CharField(max_length=32) alg_data = models.TextField(blank=True, null=True) alg_score = models.FloatField() snippet = models.ForeignKey('Snippet') child = models.ForeignKey('Child') last_seen = models.DateTimeField(editable=True, blank=True, null=True) The full stack trace when creating: File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 83. return self.dispatch(request, *args, **kwargs) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 483. response = self.handle_exception(exc) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 443. self.raise_uncaught_exception(exc) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 480. response = handler(request, *args, **kwargs) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/croinc/babycroinc/bc_views/rest.py" in timeline_questions_reshuffle 309. queryset = child.reshuffle_timeline_questions(self.TIMELINE_QUESTIONS_COUNT) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/croinc/babycroinc/bc_models/core.py" in reshuffle_timeline_questions 346. self.generate_question_set(num) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/croinc/babycroinc/bc_models/core.py" in generate_question_set 294. new_questions = self.generate_random_timeline_questions(count_q) File "/home/www/public_html/croinc.org/baby-croinc/croinc-baby-croinc.baby-croinc/croinc/babycroinc/bc_models/core.py" in generate_random_timeline_questions β¦ -
not able to update database in django. can anyone help me?
#models.py class RentalProperty(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) property = models.ForeignKey(Property,on_delete=models.CASCADE) rent_amount = models.IntegerField(default=0) class Meta: verbose_name = 'RentalProperty' verbose_name_plural = 'RentalProperties' def __str__(self): return self.property.proname #forms.py class ToLetForm(forms.ModelForm): class Meta: model = RentalProperty fields = ['rent_amount',] #views.py @login_required(login_url='/account/login/') def to_let_view(request,id = None): property_instance = get_object_or_404(Property,id = id) form = ToLetForm(request.POST or None , instance=property_instance) if form.is_valid(): form_instance = form.save(commit=False) form_instance.user = request.user form_instance.property = property_instance form_instance.save() return redirect('/account/dashboard/manage_property/properties/') context = { 'form':form } return render(request,"dashboard/tolet.html",context) I need to edit and update the already existing value in the database.Please check and tell me if any problem and how to proceed. Thanks -
How to save m2m field on Django with commit=False?
I'd like to be able to save m2m fields, but I'm having an issue where I face this error : ValueError: : "..." needs to have a value for field "id" before this many-to-many relationship can be used. Here's my models.py : class Font(models.Model): name = models.CharField(max_length=255) ... class UserInfo(models.Model): organisation = models.CharField(max_length=255) font = models.ManyToManyField(Font) ... I am not using modelForm for the many to many field. I get my values with ajax, here's what it looks like on (pdb) request.POST : <QueryDict: {'fonts': ['2', '5', '6'], 'organisation': ['COMPANY'], 'csrfmiddlewaretoken': ['...']}> what's inside 'fonts' are the id of Font. views.py ... save_it = form.save(commit=False) save_it.organisation = request.POST.get('organisation') for font in request.POST.getlist('fonts'): fonts = Font.objects.filter(id=font) save_it.font = fonts.first().id #error on save_it.font save_it.save() save_it.save_m2m() ... What am I doing wrong ? -
What is the simplest way to turn a python script into a webapp?
I do programming as a hobby. I use java and python and I know HTML. I wrote the following python script. I want to turn it into a webapp. That is you go onto the webpage you press a button , the script runs on the server it picks wav files in a random order pieces them together and then I want the link to the wav file to appear on the webpage so that the user can play it. I also want the solutions to be displayed onto the webpage. I have looked into flask and and django and it is a bit daunting. It seems that it is all about databases and authentication I couldn't find a tutorial that would do something similar to what I am trying to do here. If you have any pointers I would be grateful. What should I look into ? What is the easiest solution for what I am trying to do. What technology should I use ? Thank you in advance for your help. import wave import random def concatenate_multiple_files(infiles): while len(infiles) >= 2: raw_files = infiles[0:2] outfile = "sound_to_play_in_browser.wav" data = [] for infile in infiles: w = wave.open(infile, 'rb') β¦ -
Django Python application not working
I've successfully got Python and Apache working and Django to a point on Windows. The little Helloworld script on mod_wsgi docs runs fine. The issue that I'm coming against is I have the following in my httpd.conf: LoadModule wsgi_module /usr/envs/env/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd WSGIPythonHome /usr/envs/env <VirtualHost *:80> DocumentRoot /www/site/ ServerName example.com WSGIScriptAlias /blog /www/site/myblog/wsgi.py <Directory /www/site/myblog> Order deny, allow Allow from all </Directory> </VirtualHost> Now, whenever I go to example.com/blog I get a response of "The requested URL /blog was not found on this server." I'm obviously missing something and normally I can track it down via Google, but my Google-Fu is failing me. Also important to note, there are no errors being logged by Apache. -
Uploading Multiple Files via Admin and Model in Django
I'm building a very basic application (my first Django app). And I wanted the user to add a book in the database. So, I have one model that adds a book, along with its Name and an Image (Book Cover). This is working just fine. Now, I wanted to upload chapters for this book and a chapter will have multiple pages, so multiple files (say, .pdf files). I made another class for the chapters and have linked this class via ForeginKey. I looked over a few answers here on SO, reddit and some random blogs and all of them seem to be out of date, old or not working. I'm adding all this information by using the default admin view that we get in the Django. I'm not sure how to go about this now. I don't want multiple FileField, because the number of pages in a chapter is unknown. Any hints? My models.py is like this : from django.db import models from django import forms def book_upload_location(instance, filename): return '{}/{}'.format(instance.book_name, filename) def book_chapter_upload_location(instance, filename): # /media/book_Name/Chapter_Number/ return '{}/{}/{}'.format(instance.book.book_name, instance.chapter_number, filename) class book(models.Model): book_name = models.CharField(max_length=500) book_description = models.TextField(max_length=4000) book_author = models.CharField(max_length=250) book_genre = models.CharField(max_length=100) book_image = models.FileField(upload_to=book_upload_location) def __str__(self): β¦ -
Vue.js - Props are undefined in component method
I am beginning to integrate Vue.js in to a Django project (multi-page application). To start I am trying to create a simple logout component that will POST to the route for logout. The endpoint for the route comes from Django's url template tag. The endpoint prop is undefined within the component method. Though it is available within the component template. What am I doing wrong? Django Template <div id="logout"> <logout endpoint="{% url 'account_logout' %}" csrf_token="{{ csrf_token }}"></logout> </div> {% render_bundle 'logout' %} logout.js import Vue from 'vue' import Logout from './Logout.vue' new Vue({ el: '#logout', components: { Logout } }); Logout.vue <template> <div> <span class="logout-link" @click="performLogout"> Logout </span> </div> </template> <script> export default { name: 'logout', props: [ 'csrf_token', 'endpoint' ], data () { return { } }, methods: { performLogout: event => { console.log(`Endpoint: ${this.endpoint}`); // <-- undefined // this.$http.post(this.endpoint); } } } </script> <style> .logout-link { padding: 3px 20px; cursor: pointer; } </style> -
What's the best way to query this data with Django ORM?
I have a model like this: class Task(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tasks_by_me') assignees = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='tasks_assigned_to_me') And i want to fetch "all tasks (without duplicates) that were either created by TheUser or assigned to Him". Here's a way i might code this in SQL: SELECT * FROM ( SELECT 1 AS id, 1 as created_by_id UNION ALL SELECT 2 AS id, 2 as created_by_id UNION ALL SELECT 3 AS id, 3 as created_by_id UNION ALL SELECT 4 AS id, 2 as created_by_id ) task LEFT JOIN ( SELECT 1 AS task_id, 1 AS user_id UNION ALL SELECT 1 AS task_id, 2 AS user_id UNION ALL SELECT 2 AS task_id, 1 AS user_id UNION ALL SELECT 2 AS task_id, 2 AS user_id UNION ALL SELECT 2 AS task_id, 3 AS user_id UNION ALL SELECT 3 AS task_id, 3 AS user_id UNION ALL SELECT 4 AS task_id, 2 AS user_id ) task_assignees ON task_assignees.task_id = task.id AND COALESCE(task_assignees.user_id, 2) = 2 WHERE task.created_by_id = 2 OR task_assignees.user_id = 2; Output: id created_by_id task_id user_id 1 1 1 2 2 2 2 2 4 2 4 2 Note: there's only 1 row for task_id=2 despite the fact that it has 3 assignees and β¦ -
Efficient ways of randomizing treatments in oTree
I am writing the code for the experiment I am going to run in my master thesis. I am basically done, but I am stuck with one last aspect I cannot find the way to solve. I have a public good game with 16 participants, divided in 8 two-players groups. I have 4 treatments and I balanced the game, s.t. every treatment is played by 4 players each round (they are 12). The part I am missing at the moment is that I would like that every player does play every round exactly 3 times. This randomization is executed in the code below, which theoretically works, but practically I never managed to get to the end of it. in 20 minutes I managed to get at the end of Round 10, but could not make the program find a combination that satisfies the two conditions above for round 11 and 12. I know it is a bit tricky and it is easier to understand if you are into it, but... do you have any suggestions? Thanks a lot! class Subsession(BaseSubsession): def before_session_starts(self): info_condition = ['Bel', 'Bel', 'Act', 'Act', 'Ctrl', 'Ctrl', 'No', 'No'] i = 0 condition = True while condition: β¦ -
Getting JSON data within a js file In Django Framework
I tried to render a table using D3.js. Everything works well until my javascript function try to get data (via d3.json). I got the error message: Not Found: /bottom_up_fund/AJVF/{% url 'bottom_up_fd:data_key_statistics' fund %} [24/Jun/2017 13:52:48] "GET /bottom_up_fund/AJVF/%7B%%20url%20'bottom_up_fd:data_key_statistics'%20fund%20%%7D HTTP/1.1" 404 3467 I try to put the relative path directly but I got the same kind of error message. I am pretty sure that the solution is easy but I really don't find why it returns a wrong path whereas in my urls, each name is unique. Many thanks in advance for your help. Application url: from . import views from django.conf.urls import include, url urlpatterns = [ url(r'^fund/', views.fund, name="fund"), url(r'^fund_list/', views.fund_list, name="fund_list"), url(r'^(?P<fund>[\w-]+)/$', views.fund_dashboard, name='fund_dashboard'), url(r'^api/data_key_statistics/([\w-]+)', views.data_key_statistics, name = 'data_key_statistics') ] Project url: from django.conf.urls import include, url from django.contrib import admin from django.contrib.sitemaps.views import sitemap from FundBlog.sitemaps import PostSitemap from django.conf import settings from django.conf.urls.static import static sitemaps = { 'posts': PostSitemap, } urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/', include('account.urls')), url(r'^FundBlog/', include('FundBlog.urls', namespace = 'FundBlog', app_name = 'FundBlog')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), url(r'^bottom_up_fund/', include('bottom_up_fd.urls', namespace = 'bottom_up_fd', app_name = 'bottom_up_fd')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) application view: For clarity, I put only the view that return β¦ -
Get class diagram for Django application [on hold]
I am just half way writing my django application and my employer wants me to fetch him class diagram of the whole code written until now. As I'm really short in time i started thinking of a tool that will do it for me in a shorter time. i have tried Pyreverse But it seems the docs are long and not as straight forward as my tight time requires. So at very first step please tell me if does Pyreverse satisfy this purpose and then give me a simple line of command that will make it draw the diagram for me. if not, please give me better idea's on this issue. thanks. -
Flask_admin with mongo db - name ' ' is not defined
Hi i have a dashboard that register users (publisher or advertiser) with registration are in a pending state. I used from flask_admin import Admin from flask_admin.contrib.pymongo import ModelView after db connection i use admin = Admin(app, name='Admin dashboard', template_mode='bootstrap3') from this point i can get into admin but obviously i don't have nothing there. i do admin.add_view(ModelView(Publisher['users'], db.section)) but get the error NameError: name 'Publisher' is not defined (my objective is show the publisher tab in the admin with the publisher users, and the same for advertisers.... i have a Models.py to generate the user_schema this is my code. can someone get me into the right direction... best Models.py file http://www.creativelab.pt/Models.py Index.py File http://www.creativelab.pt/index.py -
AttributError: 'NoneType' object has no attribute 'exc_info'
I am facing the following error in my Django project when I run on staging, but I face no error on my local machine: Unhandled exception in thread started by <function wrapper at 0x7f28cb57e500> Traceback (most recent call last): File "/root/.virtualenvs/thakurani/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper _exception = sys.exc_info() AttributeError: 'NoneType' object has no attribute 'exc_info' -
Django models foreignkey group calculation
I have two models. class A(models.Model): id = models.IntegerField() name = models.CharField() class B(models.Model): item = models.ForeignKey(A) view = models.IntegerField() name = models.CharField() I want to get the lists of A and when I get the list I want to calculate the how many (numbers) class B mapped with particular A and how many has viewed (view=1) ? Example: A id | name 1 | A1 2 | A2 B item_id | name | view 1 | B1 | 1 1 | B2 | 1 1 | B3 | 0 2 | B4 | 0 output: something like this. [ { id : 1 name: A2 num_of_item: 3 num_of_view: 2 } { id : 2 name: A2 num_of_item: 1 num_of_view: 0 } ] What is the efficient way of doing it. ? Thanks -
How can I delete a user account in Django Rest Framework?
I am creating an application by combining Django Rest Framework and Angular. Please let us know about the implementation of user deletion, because there are places that will not work. I described in Djnago's views.py about the deletion view as follows. class AuthInfoDeleteView(generics.DestroyAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = AccountSerializer lookup_field = 'email' queryset = Account.objects.all() def get_object(self): try: instance = self.queryset.get(email=self.request.user) return instance except Account.DoesNotExist: raise Http404 In addition, I write in serializer.py as follows. from django.contrib.auth import update_session_auth_hash from rest_framework import serializers from .models import Account, AccountManager class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'username', 'email', 'profile', 'password', ) def create(self, validated_data): return Account.objects.create_user(request_data=validated_data) In this state, when sending a method of Angular to DELETE to the URL(/api/user/delete/) to which AuthInfoDeleteView is linked, the following error occurred. TypeError: 'bool' object is not callable [24/Jun/2017 10:21:53] "DELETE /api/user/delete/ HTTP/1.1" 500 15690 How can I properly delete accounts correctly? I need your help. -
show map instead of blue background color
I am using gis for location based app. I have imported models of gis to show location field which is a PointField. My app is running but is showing the location blue background instead of map. Below is the screenshot Why map is not shown? Here is the code i have done from django.contrib.gis.db import models class Property(models.Model): """Model for all properties.""" owner = models.ForeignKey(settings.AUTH_USER_MODEL) address = models.CharField(_('Address'), max_length=140) location = models.PointField(max_length=40, null=True) prefered_radius = models.IntegerField(default=5, help_text="in kilometers") objects = models.GeoManager() -
Rest API tocken based authentication. Basic Auth
I have implemented token based authentication using rest_framework, every thing is working fine as of now but I have one question that if I am sending user-name and password in header using basic-auth then why am I required to send user-name and password with payload. When I sending request containing payload with user-name and password in body section with out user-name and password in header of request, I am getting following as response: { "detail": "CSRF Failed: CSRF token missing or incorrect." } while I am sending user-name and password in header with out sending user-name and password with payload, I am getting following response: { "detail": "Invalid username/password." } Why am I required to send user-name and password in header section while I am sending it with payload. I am not quite sure about the concept. Could anyone please explain and show me the right way to do it. I have used this reference. Following is my code: authuser.py """Authentication classes for Django Rest Framework. Classes: ExpiringTokenAuthentication: Authentication using extended authtoken model. """ from rest_framework import exceptions from rest_framework.authentication import TokenAuthentication from rest_framework_expiring_authtoken.models import ExpiringToken class ExpiringTokenAuthentication(TokenAuthentication): """ Extends default token auth to have time-based expiration. Based on http://stackoverflow.com/questions/14567586/ β¦ -
Specifying dynamic file upload location
So, I just started learning Django and I wanted to make an app. It's a simple app and I've just initialized my admin view and then I have a model named "Book". It's just like information about a book. The user can enter book name, author, description and upload a book cover image. I got this working without a hiccup. But, currently, the image is being saved in the "/media" folder, because that's what I specified in the MEDIA_ROOT of the settings file (which is totally fine). Now, what I want is that instead of this in my models.py, it gets saved to it's own directory. For example : Book Name : If god was a banker I want the cover image to be saved in "/media/albums/If God Was A Banker". How can I do this? I looked into the "upload_to" attribute of the "FileField". So, I tried something like this : book_name = models.CharField(max_length=500, allow_blank=False,trim_whitespace=True) comic_image = models.FileField(upload_to='%s/' % book_name) and of course this didn't work, as book_name didn't return the str type (I knew it'll go wrong though). So, how can I get this to work? anything I'm missing or anything that I could do to achieve my β¦