Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting error as Error importing module: 'SecretBallotIpUseragentMiddleware doesn't look like a module path' for django-secretballot package
I am trying to add like button to my django project. But I am stuck with an error. Please help me to figure it out. File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/wsgi.py", line 153, in __init__ self.load_middleware() File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/usr/local/lib/python3.4/dist-packages/django/utils/module_loading.py", line 18, in import_string six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.4/dist-packages/django/utils/module_loading.py", line 15, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ImportError: SecretballotIpMiddleware doesn't look like a module path During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/runserver.py", line 142, in inner_run handler = self.get_handler(*args, **options) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/usr/local/lib/python3.4/dist-packages/django/core/servers/basehttp.py", line 59, in get_internal_wsgi_application sys.exc_info()[2]) File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.4/dist-packages/django/core/servers/basehttp.py", line 49, in get_internal_wsgi_application return import_string(app_path) File "/usr/local/lib/python3.4/dist-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File … -
Django: Store gmt time in database table instead of local time
In my customer model I have two datetime fields for storing created and updated time. datetime_created = models.DateTimeField(auto_now_add=True) datetime_updated = models.DateTimeField(auto_now=True) When I create a customer, Now it is storing the local time in the database, When I get this customer data through API, It is returning the datetime in gmt time. This is fine. But I want to save the gmt time in the database. I think storing local time in database is not a good practice. Date settings in settings.py file is LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I have already installed "pip install pytz" module and my database is postgresql. -
400 using Axios to make a post request to Django Rest Framework
I'm working with learning some javascript to make a post to a little rest API I created with django rest. I have a post that works when I was working with jQuery but now I am reimplementing using Vue.js and am hitting a snag. When I do the below post request I get a 400 error and am not sure what I am missing. I would imagine something with my header is incorrect? Any advice would be welcome. axios({ method: 'post', url: '/api/matches/', data: JSON.stringify(data), headers: { "X-CSRFToken": csrfToken, "Content-Type": "application/json" } }) jQuery post for reference: $.ajax({ type: "POST", url: "/api/matches/", data: JSON.stringify(final_data), success: function() {}, error: function(err) {console.log(err)}, contentType: "application/json; charset=utf-8", dataType: "json", crossDomain:false, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); -
Django - chart do not display correctly
The goal here is to show each bar corresponding to association and total members as displayed below: What I get is this one big block with no value. Seems that no one has the same issue here that I have been looking for. Still a newbie so appreciate all your help & guidance, folks! models.py class Member(models.Model): member_no = models.AutoField(primary_key=True) association = models.ForeignKey('Association') ... class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.asoc_name def __unicode__(self): return self.asoc_name class AssociationSummary(Association): class Meta: proxy = True verbose_name = 'Association Summary' verbose_name_plural = 'Association Summary' admin.py @admin.register(AssociationSummary) class ChartAssociationAdmin(admin.ModelAdmin): change_list_template = 'admin/chart_association.html' def changelist_view(self, request, extra_context=None): response = super(ChartAssociationAdmin, self).changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'association': Count('asoc_name'), 'total': Count('member'), } response.context_data['summary'] = list( qs.values('asoc_name', 'member').annotate(**metrics) ) response.context_data['summary_total'] = dict( qs.aggregate(**metrics) ) summary_over_time = qs.values('asoc_name', 'member').annotate(total=Sum('member')) summary_range = summary_over_time.aggregate( low=Min('total'), high=Max('total'), ) high = summary_range.get('high', 0) low = summary_range.get('low', 0) response.context_data['summary_over_time'] = [{ 'asoc_name': x['asoc_name'], 'total': x['total'] or 0, 'pct':\ ((x['total'] or 0) - low) / (high - low) * 100 if high > low else 0, } for x in summary_over_time] return response chart_association.html {% extends 'admin/change_list.html' %} {% block content_title … -
list index out of range django
Can someone explain me why am I getting back list index out of range, it occur in two places in my view, first one is in context_data = self.get_context_data(user_id, month, year, form=form) and context['month'] = calendar.month_name[month], so can someone explain me what is happening in my code. Here is a full Traceback my view: import calendar import datetime from django.contrib import messages from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from django.shortcuts import redirect, get_object_or_404 from django.views.generic.edit import FormView from .helpers.user_util import get_user_full_name_or_user_name from models import Rate from statistics.forms import CommissionsMonthSelectionForm from statistics.services import ManagerCommissionsProjectsCalculation, CommissionsAccessService class UserSalesCommissionsView(FormView): template_name = "statistics/user_sales_commissions.html" form_class = CommissionsMonthSelectionForm currency = Rate.EUR def get(self, request, *args, **kwargs): user_id = self.kwargs['user_id'] requesting_user = request.user if CommissionsAccessService.can_view_commissions_page(requesting_user, user_id): month = int(self.request.GET.get('month', datetime.datetime.now().month)) year = int(self.request.GET.get('year', datetime.datetime.now().year)) form = CommissionsMonthSelectionForm(initial={'year': year, 'month': month}) context_data = self.get_context_data(user_id, month, year, form=form) return self.render_to_response(context_data) else: return HttpResponseForbidden('Access denied') def post(self, request, *args, **kwargs): user_id = self.kwargs['user_id'] requesting_user = self.request.user if CommissionsAccessService.can_view_commissions_page(requesting_user, user_id): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form, user_id) else: return self.form_invalid(form) else: return HttpResponseForbidden('Access denied') def form_valid(self, form, user_id=None): year = form.cleaned_data['year'] month = form.cleaned_data['month'] return redirect(self.get_success_url(user_id, month, year)) def form_invalid(self, form): … -
from apps.notification import models as notification ImportError: No module named notification
Getting this error suddenly on working project in Django. from apps.notification import models as notification ImportError: No module named notification -
Evennia server connect fail
When I tried Evennia Quickstart,I start server by command evennia -i start but when I use browser to open localhost:8000 and clicked 'play online',it report: The connection was closed or lost. I haven't edit any code of the game -
Django, m2m count annotation related model with condition
so my models: class User(models.Model): username = models.CharField(max_lenght=255) class Group(models.Model): users = models.ManyToManyField('User') class ActiveGroup(models.Model): group = models.ForeignKey('Group', null=True, blank=True, default=None) user = models.OneToOneField('User') So the deal is every user can be a member of any group ( which is represented by m2m field on Group model). But can be active member in only one of them at the same time ( thats why oneToOneField relation on activegroup model). Problem: need to make a queryset for Group models with count of users which are active. so its suppose to be like SELECT group.id, COUNT( SELECT COUNT(*) FROM activegroup WHERE activegroup.group_id = group.group.id ) as users_count FROM group. I've tried django.db.models Case and When things but nothing helps. -
Celery hangs without error
My celery tasks hangs in the middle of task process. It is started from yesterday, before it works ok. For example during model.objects.get(*args, **kwargs) and not for all models. No error, no crash, nothing. How can I solved it? -
django.db.utils.OperationalError: near "[]": syntax error
there is this error showing after i have used makemigrations command i have tried commenting different column for it but it wont work C:\Users\Rushabh\Desktop\project\MyPrj>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, paper, sessions Running migrations: Applying paper.0014_auto_20170405_1549...Traceback (most recent call last): File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "[]": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field self._remake_table(model, create_fields=[field]) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table self.create_model(temp_model) File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 295, in … -
How do I use Bcrypt. Trying to see what the actual code looks like.
My question, where and how do I implement Bcrypt in django/python. I'm still in learning. I've read the documentation. I you add the hashed line in settings.py but in actual code. Here is what I have in my models.py and views.py. I know what I have is wrong. When I try to log in, I can type any password and it logs me in. All and any help would be much appreciated. Thank you in advance. ** in models.py** from future import unicode_literals from django.db import models from django.contrib import messages import bcrypt import re from django.conf import settings EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]+$') class UserManager(models.Manager): def validate(self, data): flag = True errs = [] if len(data['first_name']) < 2: flag = False errs.append("First cannot be less than 2 characters.") if not data['first_name'].isalpha(): flag = False errs.append("First name must not contain numbers.") if len(data['last_name']) < 2: flag = False errs.append("Last cannot be less than 2 characters.") if not data['last_name'].isalpha(): flag = False errs.append("Last name must not contain numbers") if not EMAIL_REGEX.match(data['email']): flag = False errs.append("This is an invalid email.") if data['pass'] != data['c_pass']: flag = False errs.append("Your passwords do not match.") if flag: # messages.success(request, "Success! Welcome, " + userInfo['first_name'] + "!") hashed … -
View Stats Code Coverting From PHP to Python
I am switching my web site from PHP to Django (Python 3.5). I am needing help converting the following view statistics function into Python. The database structure is as follows: CREATE TABLE blog_website_view_stats ( reference bigserial NOT NULL, blog_website_reference bigint NOT NULL, language_iso text NOT NULL, year bigint NOT NULL, month bigint NOT NULL, day_1 bigint, day_2 bigint, day_3 bigint, ... total_month_views bigint NOT NULL, ) This is the PHP code /** * Entry View Stats * * @param $blog_reference */ public function EntryViewStats( $blog_reference ) { /** * @var \Actsministries\Database\Entity\RonsHome\BlogWebsiteViewStats $result */ $result = $this->entityManager->getRepository('Actsministries\Database\Entity\RonsHome\BlogWebsiteViewStats') ->findOneBy( [ 'blogWebsiteReference' => $blog_reference, 'languageIso' => 'en-US', 'month' => date('n'), 'year' => date('Y') ] ); if (!is_object($result)) { $setday = 'setDay' . date('j'); $this->entityManager->beginTransaction(); // does not exist $view_stats_update = (new EntityBlogWebsiteViewStats())->setBlogWebsiteReference($blog_reference) ->setLanguageIso('en-US') ->setMonth(date('n')) ->setYear(date('Y')) ->setTotalMonthViews('1') ->$setday( '1' ); $this->entityManager->persist($view_stats_update); $this->entityManager->flush($view_stats_update); $this->entityManager->commit(); } else { $this->entityManager->beginTransaction(); $setday = 'setDay' . date('j'); $getday = 'getDay' . date('j'); $result->$setday($result->$getday() + 1); $result->setTotalMonthViews($result->getTotalMonthViews() + 1); $this->entityManager->persist($result); $this->entityManager->flush($result); $this->entityManager->commit(); } } The python code I've come up with so far is: @transaction.atomic() def stats(self, context): """stats :param dict context: Context :return: None|bool """ result = BlogWebsiteViewStats.objects.update_or_create( blog_website_reference=1, language_iso='en-US', year=timezone.now().year, month=timezone.now().month, ('day_' + str(timezone.now().day))=datetime.utcnow() + timedelta(days=1), total_month_views=1 ) … -
DRF occur error message "error": "unsupported_grant_type" in AngularJS but well work in python
i have been made API with Django RestFramework it's well work in python code below 1 import json 2 import requests 3 4 class AccessToken: 5 def __init__(self, url, username, password, client_id, client_secret): 6 self.token_url = url 7 self.client_id = client_id 8 self.client_secret = client_secret 9 self.data = [ 10 ("grant_type", "password"), 11 ("username", username), 12 ("password", password), 13 ] 14 15 16 def get(self): 17 print('get') 18 r = requests.post(self.token_url, data=self.data, auth=(self.client_id, self.client_secret)) 19 print(dir(r.request)) 20 print('body: ', r.request.body) 21 print('headers: ',r.request.headers) 22 print('method: ', r.request.method) 23 print('url: ', r.request.url) 24 25 r = r.json() 26 return r.get('access_token') result below ('body: ', 'grant_type=password&username=tester%40example.co.kr&password=test123%21') ('headers: ', {'Content-Length': '76', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.12.4', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic Q1IwcXRBU2NDSDdzcEZJUUplVlJZQ3lIa2RIYzV0cldJcnNadFJ5UzpZN1VKalZBUUpxckthV3VUMUtZYVpxd01DZ2VMOVZCT0NoS1pKRFQxQkRpa0ZUSG5sQ0ZCN0JTUjAxeE1hRXlsd2tnUHNNNGE0dVdhS3RvRWtITzNnYzlYcmZzZFFwVUpwSURYZ2NlbmNCZnRUM3lyVGRFNFVMeElLTUV6SWkxRg=='}) ('method: ', 'POST') ('url: ', 'http://my.api.server.co.kr/api/v2/o/token/') and i tried AngularJS with below code $http.post ("http://v2dev.refreshclub.co.kr/api/v2/o/token/", { "client_id": "CR0qtAScCH7spFSDGHRSEEGdHc5trWIrsZtRyS", "client_secret": "Y7UJjVAQJqrKaWuT1KDSFGEWgeL9VBOChKZJDT1BDikFTHnlCFB7BSR01xMaEylwkgPsM4a4uWaKtoEkHO3gc9XrfsdQpUJpIDXgcencBftT3yrTdE4ULxIKMEzIi1F", "grant_type": "password", "username": "tester@example.co.kr", "password": "test123!" }); finally i got this return value "error: unsupported_grant_type" i don't know why result is different please help me!! T.T -
get all from table django not only __str__(self)
models.py class club(models.Model): name = models.CharField(max_length=30) city = models.CharField(max_length=30) premiere_leauge = models.BooleanField(default=False) def __str__(self): return self.name Views.py ... a = request.POST['club'] b = request.POST['city'] result = club.objects.all.get(name__exact=a, city__exact=b) .... All is fine, however I believe result returns me: def __str__(self): return self.name Whatsover, I would like an equivalent of 'SELECT * FROM APP_CLUB where name='something and city='something'; so i would be able to do further manipulation in django like: if result[3] is True: do_something() -
The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'shop.Product'
Here is my admin.py file content from django.contrib import admin from .models import Category, Product class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Category, CategoryAdmin) class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'price', 'stock', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated'] list_editable = ['price', 'stock', 'available'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Product, ProductAdmin) Here is the traceback error which I have no idea on how to solve I'm currently using the book Django by example learn the web framework and the error m getting is scarry ERRORS: <class 'shop.admin.ProductAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'shop.Product'. <class 'shop.admin.ProductAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'name', which is not an attribute of 'shop.Product'. <class 'shop.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'shop.Product'. <class 'shop.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'slug', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'shop.Product'. <class 'shop.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'price', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'shop.Product'. … -
How to upvote/like a post in django
I am a beginner to django programming. I have been trying to add a like button to the post which is posted by the user. In my models.py class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Please help in adding a like button to my blog. -
Django: How to use parent table fields in 'limit_choices_to'?
I have two classes System and Station which inherit from Base. The Base class has a foreign key to Group and Station has a foreign key to System. I am trying to place a 'limit_choices_to' constraint on the latter FK, so that the related System has to be from the same Group as the Station. Here's a snippet of the models.py class Base(models.Model): group = models.ForeignKey(Group) class System(Base): ... class Station(Base): system_info = models.ForeignKey(System, limit_choices_to={'group': 'self.group'}) I've tried a number of ideas, including what is above, but no luck. Any help will be much appreciated! -
django complex queries filter and create list
class or models class Category(models.Model): category_name = models.CharField(max_length=50) company_name = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): return self.category_name class Product(models.Model): product_name = models.CharField(max_length=50) category = models.CharField(max_length=50) desc = models.CharField(max_length=120) company_name = models.CharField(max_length=50, default=None) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) class ProductDetails(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) batch = models.CharField(max_length=50) quantity = models.IntegerField() cost = models.FloatField(null=True, blank=True, default=None) mfg = models.DateTimeField() exp = models.DateTimeField() timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) class product_barcode(models.Model): batch = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) barcode = models.BigIntegerField() flag = models.IntegerField() timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) 1> first task find product_name,cost,flag?? using barcode value of product_barcode table class S_history class S_History(models.Model): barcode = models.CharField(max_length=500) email = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) 2> create list if S_History.barcode=prodcut_barcode.barcode S_History table may contain multiple entries of same barcode list look like [{"product_name":"fff","cost":"999"},{"product_name":"xxxwww","cost":"55"}] -
Django user daily updating model
I'm new in django. I want to create applications where users will be able to create objects and update them daily (add new days and new descriptions and photos). So my question is: 1. In models.py I need to create class Object(models.Model) and use ForeignKey(settings.AUTH_USER_MODEL) or OneToOneRel(settings.AUTH_USER_MODEL) to connect user which create object with this object ? 2. I need to create an extra class day where there will be fields such as a subtitle description etc and add it to the object class? 3. How I can create form or views to daily updating ? -
How to set webhook for facebook lead creation?
I am new facebook API.I need setup webhook for lead generating at my ads. I checked facebook developers docs but I didn't find any solution. I have find webhook setup of page subscriptions.But I need... How to setup webhook for tracking for ad leads on facebook page. Any one can help me?Thanks in advance. -
pymongo : to check if we have connected to MongoDB database
client = MongoClient('localhost',27017) db = client[DB_NAME] def db_connect(): #connecting to a DB in mongoDB try: if client.get_database(DB_NAME): print("Connection Successful!") return True except: print("Please check your connection") return False def db_close(): print ("Connection Getting Closed") client.close() I am trying to achieve a task, only if the connection exists by pymongo, then return True so that the functions can proceed, else it should return False and a message to check connection. So that we don't proceed further. How can I achieve this? -
Django filename for uploaded file
I am working on some legacy code and recently I migrated the app from Django 1.5 to 1.8 . I have this model where the user uploads files. This is the model: class Document(models.Model): file = models.FileField(upload_to='common/') user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='documents') created = models.DateTimeField(default=timezone.now) modified = models.DateTimeField(auto_now=True) del_f = models.BooleanField(default=False) class Meta: ordering = ['-created',] app_label = 'dms' def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Document, self).save(*args, **kwargs) @property def filename(self): return os.path.basename(self.file.name) I am trying to change the filename property. The filenames tha are generated now are these: I want that weird "_WtyGVsQ" before the file extension to be replaced with an ascending number(the file extension stays). For example if I upload the file "data_conversions.ods" 2 times ,the filenames that will be generated will be: data_conversions_1.ods data_conversions_2.ods ..and so on... The odd fact is that in 1.5 the filenames where uploaded like that (with the _1,_2 ascending). Any suggestions? -
drf: custom field validation function not being called
I have a following serializer: class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True) image = Base64ImageField(required=False) def validate_image(self, value): import ipdb ipdb.set_trace() # if value.get('fileArray', None): # if value.get('dataURL', None): # return value.get('dataURL') # else: # raise serializers.ValidationError("No file data present") # else: # return None class Meta: model = Question fields = ('id', 'detail', 'image', 'true_false_answer', 'type', 'choices') Then in view: serializer = QuestionSerializer(data=data) serializer.is_valid() This gives me False and: serializer.errors gives: {'image': ['The submitted data was not a file. Check the encoding type on the form.']} What I found is validate_image is never called. What might be the problem? -
Django REST framework auto decode while rendering URLs
I'm using a ModelViewSet with HyperLinkedSerializer to show my objects in the browsable APIs. The problem is that one field of them is an URL like "download_url": "https://f1234567.s3.amazonaws.com/backup/89045%40BASE-175", Copying this URL in the problem, it successfully downloads the target file, however clicking on this link from the DRF it goes to https://f1234567.s3.amazonaws.com/backup/89045@BASE-175 where it decoded the %40 back to @ My question is how to fix this and make the links in the browsable APIs safe for clicks and which part is responsible for auto decoding the URLs. BTW, requesting the same API URL http://127.0.0.1:8000/api/v1/backup_files/14/ but with JSON content type, the download_url value is valid with %40 not @. -
DRF making DateTimeField naive without considering default timezone
The default timezone is TIME_ZONE = 'America/Chicago' and USE_TZ = False In the request data, I have time field whose value is something like this: '2017-04-05T14:42:52.472+05:00' And when I do this: serializer = self.get_serializer(data=data) if serializer.is_valid(): ... that time field is converted to this inside validated_data: 2017-04-05 09:42:52.472000 That is, it is making the time naive. However, it is not considering my default timezone. I would expect it to convert the time to Chicago time first and then make it naive to this: 2017-04-05 04:42:52.875000 just like how django.utils.timezone.make_naive() works. I am solving this by using that make_naive. However, I don't think this is a good solution. Serializer: class LocationSerializer(serializers.ModelSerializer): time = UnixTimestampField() class Meta: model = Location fields = ( 'latitude', 'longitude', 'time' ) def validate(self, attrs): user = self.context['request'].user if user.is_authenticated(): attrs['tracking_id'] = user.tracking.id attrs['device_id'] = user.current_device.id return attrs Is this the default behavior of DRF? What is the proper way of solving this?