Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django mezzanine multiple blogs on same site
I'm using Mezzanine for my blog and I want to add another page similar to the blog but separate in design and structure. Is this possible to do within 1 mezzanine project? -
Django 1.10 shows a square bracket in display of the form
I'm quite new to django and i'm now creating my forms for uploading data in the database. I'm using django 1.10 and python 2.7 I have a upload.html in my templates. And then i <div class="form">] <form method="post" action="{% url 'upload' %}" enctype=multipart/form-data > {% csrf_token %} <!-- This line inserts a CSRF token. --> <table> {{ form.as_table }} <!-- This line displays lines of the form. --> </table> <p><input type="submit" value="Create" /></p> </form> </div> A part of my forms.py class Form_inscription(forms.Form): study = forms.ModelChoiceField(label="Choose the study of the database file", queryset=Study.objects.all(), initial=Study.objects.all()[:1].get().id) databasefile = forms.FileField(label="Database file") assay = forms.ModelChoiceField(label="Choose the assay", queryset=LookUpAssay.objects.all(), initial=LookUpAssay.objects.all()[:1].get().id) readout = forms.ChoiceField(label="Choose the readout, choose --- if assay contains all readouts", choices=readouttuple) rawdatafile = forms.FileField(label ="Choose the raw data file") It then displays this with the square bracket. and i have no idea why. ] Choose the study of the database file: Database file: Choose the assay: Choose the readout, choose --- if assay contains all readouts: Choose the raw data file: Could someone shed a light on this weird problem? Thanks in advance, Dani -
Skip a list of migrations in Django
I have migrations 0001_something, 0002_something, 0003_something in a third-party app and all of them are applied to the database by my own app. I simply want to skip these three migrations. One option is to run the following command python manage.py migrate <third_party_app_name> 0003 --fake But I don't want to run this command manually. I was thinking if there can be any method by which I can specify something in settings to skip these migrations. Or if there is any way to always fake 0001, 0002 and 0003. If this was in my own app, I could simply remove the migration files but it is a third party app installed via. pip and I don't want to change that. -
How to solve "table "auth_permission" already exists" error when the database is shared among two Django projects
in this question I learned how to make two Django projects use the same database. I have: projects project_1 settings.py ... project_2 settings.py ... and # project_1/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_ROOT, 'development.db'), }, } # project_2/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join( os.path.dirname(os.path.dirname(PROJECT_ROOT)), 'project_1', 'development.db' ), }, } In project_2/, when I run: python manage.py syncdb I get: django.db.utils.OperationalError: table "auth_permission" already exists I guess this happens because python fails in trying to add project_2 tables that already exists in the shared db. How can I add to the shared db only those project_2 tables not already existing in the common database? -
django export filtered query to csv
So the scenario is this: I have a search form where the user types or selects the criteria. These criteria are being posted and I get a querry in returned,filtered with these criteria. The code for the search form is similar to the code given below. What I want to do now is take these results and export them in csv file. So,as I said I have almost the same code where I get my params/criteria with GET.Basically I GET the criteria the user has typed or selected after the search POST was made. So far, I have succesfully got the params, I can see them in print, and the export is donw but I can see only the first row. It's like I can't pass the query (as provided in results). Here's my code: def get_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=mycsv.csv' if request.method == 'GET': params = {} your_values = {} context = {} field_1 = request.GET.get('field_1',None) field_2 = request.GET.get('field_2',None) field_3 = request.GET.get('field_3',None) if field_1: your_values['field_1'] = field_1 if field_2: your_values['field_2'] = field_2 if field_3: your_values['field_3'] = field_3 if field_4: your_values['field_4'] = field_4 for key, value in your_values.items(): if value: params[key] = value print('params are:',params) results = … -
range filter not working in django
I want to filter my queryset on the basis of two values. I want result between two numbers.I am trying some code but it is not working .It did not return me proper result. my code cost_gte = int(request.GET.get('cost_gte')) cost_lte = int(request.GET.get('cost_lte')) list4 = [] result = Product.objects.filter(cost__gte=cost_gte , cost__lte=cost_lte ) print result for res in result: list4.append(res.project_id) data ={'cost result':list4} return HttpResponse(json.dumps(data)) Some time it returns all product and some time it return none.I cant understand why it is not working. i also try by range result = Product.objects.filter(cost__rage=(cost_gte,cost_lte)) but is also behave same.Please guide me what i am doing wrong. -
Template Tag requires 0 arguments, 1 provided
Why can't I create a template tag with an argument like this? @register.filter def foo(value, arg): return arg And I am calling it like this: {{ params|foo:"bar" }} Which gives me: foo requires 0 arguments, 1 provided -
Python: ImportError: No module named 'tutorial.quickstart'
I am getting import error even when I am following the tutorial http://www.django-rest-framework.org/tutorial/quickstart/ line by line. from tutorial.quickstart import views ImportError: No module named 'tutorial.quickstart' where my urls.py file looks like from django.conf.urls import url, include from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Note: I have the project in Rest_Tutorial folder which consist of virtual enviroment - "env" and project "tutorial". This tutorial consist of "quickstart" and "tutorial" -
Django app defaults?
I'm looking for a way to have application defaults and settings that are easy to use, difficult to get wrong, and have little overhead.. Currently I have it organized as follows: myapp/defaults.py # application defaults import sys if sys.platform == 'win32': MYAPP_HOME_ROOT = os.path.dirname(os.environ['USERPROFILE']) else: MYAPP_HOME_ROOT = '/home' in my project I have: mysite/settings.py from myapp.defaults import * # import all default from myapp MYAPP_HOME_ROOT = '/export/home' # overriding myapp.defaults With this setup I could import and use settings in the regular django way (from django.conf import settings and settings.XXX). Problem #1: When running unit tests for the app there is no site however, so settings wouldn't have any of the myapp.defaults. Problem #2: There is also a big problem if myapp.defaults needs to use anything from settings (e.g. settings.DEBUG), since you can't import settings from defaults.py (since that would be a circular import). To solve problem #1, I created a layer of indirection: myapp/conf.py from . import defaults from django.conf import settings class Conf(object): def __getattr__(self, attr): try: return getattr(settings, attr) except AttributeError: return getattr(defaults, attr) conf = Conf() # !<-- create Conf instance and usage: myapp/views.py from .conf import conf as settings ... print settings.MYAPP_HOME_ROOT # will print … -
Invalid device token blocks whole Frame of APNS messages
I'm writing the server side of an app which uses Apple Push Notifications to signal mobile clients that there was some change on server side and they need to update themselves. Occasionally I also send some banners. After reading about Frames it would be a trivial enhancement to send a bunch of messages in one frame instead of one-by-one. (Unfortunately the frame is not a broadcast mechanism, so event though I send exactly the same content to all clients, I do need to repeat them n times. But that's not my real problem). Frame wouldn't decrease the number of bytes I send but I'd need to establish a lot less SSL connections. The problem is that every once in a while a device token becomes stale or unfavored by the APNS servers: meaning that they are reported as invalid. If I send n messages in one frame and any one of them has an invalid device token associated with it, then the whole frame's delivery seems to be ruined. So devices with valid tokens also won't get the message or the banner. Basically one rotten apple causes the whole basket of apples interpreted as rotten on the APNS server side? … -
Django query string
i have some string in database like as this: |pay_tocken | |-----------------------------------------| |d7fe6c3d52cab958a67d51a5f18a2288ad53c5ee | |00684bf8e9af13e4345297725d2804e6d04158dc | |851c4b07ab9954651f20871ed5574673e65ebe95 | when i run query for get it, return error my qyery is: def cart_items(request, tocken): pay = Pay.objects.get(pay_tocken=tocken) return render(request, 'pay/pay_items.html', {'pay':pay}) when i run it return error: Reverse for 'cart_items' with arguments '()' and keyword arguments '{u'tocken': u'dfgdf'}' not found -
How to trigger a function with checkbox django
I wanna know how I run certain functions depending on the selected checkboxes. This is my visual template: and this is the code I have for my template is called admin.html: <div class="panel-body"> <p><button type="button" class="btn btn-black"><i class="fa fa-upload" </i>&nbsp;&nbsp;<span class="bold">IMPORT ALL</span></button> </p> <p> Import selected reports:</p> <p> <label><input type="checkbox" value=""> Cisco Backlog Report</label></p> <p> <label><input type="checkbox" value=""> Planning & Standard</label></p> <p> <label><input type="checkbox" value=""> Emo Trans Report</label></p> <p> <label><input type="checkbox" value=""> Phyllis Report</label></p> <p> <label><input type="checkbox" value=""> Purchase Order View</label></p> <p> <label><input type="checkbox" value=""> On Hand Inventory</label></p> <p> <label><input type="checkbox" value=""> Bill of Material</label></p> <p> <label><input type="checkbox" value=""> Aged</label></p> <p> <label><input type="checkbox" value=""> Shipment with Times</label></p> <p><button type="button" class="btn btn-danger">Import</button> </p> As I mentioned before, I got 10 functions that read several .csv reports and upload the data into models and I trigger them with the URL section. In my views.py I will show two examples: def importpurchase(request) Log logic here def importcisco(request) Log logic here def importall(request) # this function is to import all importpurchase(None) importcisco(None) -
Django clear COOKIES sessionid
On my website I have no login system. However, users get sessionid and csrftoken, but I need to clear them up from time to time Is there any way that I can delete them manually? Thanks a lot. -
Dynamic Formset without Javascript
I wanted to create a dynamic Formset without using JavaScript, so I touched upon the following link: Dynamic Formset without Javascript Now What I actually want is something like this: (i.e how I want my forms to look like) presc_id : |______________| (a single field form for presc_id) MedicineName : |______________| Time : |______________| quantity : |____________| ( a multiple field subform for the data of a particular presc_id.) | A PLUS BUTTON (+) | (To add more data for the same presc_id.) | CREATE BUTTON | (to finally create/add/submit the data of a particular presc_id, i.e all the {MedicineNames, time, quantities} sets added using the '+' button for a particular presc_id.) Now, to the best of my knowledge, I have edited this code in the link, the following way: forms.py : from django import forms from crispy_forms.helper import FormHelper from django.forms.models import formset_factory class FormsetForm (forms.Form): delete = forms.BooleanField(required=False,initial=False) medicinename = forms.CharField(label='Medicinename', max_length=100) quantity = forms.CharField(label='Quantity', max_length=100) class SpecificForm(forms.Form): imageid=forms.CharField(label='PrescID', max_length=100 ,widget = forms.TextInput(attrs= {'required': 'true',}),) view.py : from django.shortcuts import render from django.template import loader from django.http import HttpResponse from .forms import * from .models import Prescriptions, Digitize from django.forms.models import formset_factory def index(request): if request.method == 'POST': … -
Django REST FileUpload serializer returns {'file': None}
I’ve been working on a Django project that requires a file upload. I use API approach in my app designs using django-rest-framework. I created my model, APIView, and serializer but unfortunately every time the request goes through the serializer the upload.data returns {'file': None}. If I just use request.FILES['file'] it returns the file no problem but I want to use the serialized data. Here is my code below. views.py class FileImport(APIView): parser_classes = (MultiPartParser, FormParser,) serializer = ImportSerializer def post(self, request, format=None): upload = self.serializer(data=request.FILES) if upload.is_valid(): file = FileUpload(file=upload.data['file'], uploaded_by=request.user.profile) file.save() return Response({'success': 'Imported successfully'}) else: return Response(upload.errors, status=400) serializers.py class ImportSerializer(serializers.Serializer): file = serializers.FileField() models.py class FileUpload(models.Model): file = models.FileField(upload_to='files/%Y/%m/%d') date_uploaded = models.DateTimeField(auto_now=True) uploaded_by = models.ForeignKey('UserProfile', blank=True, null=True) -
Django FormWizard Keep Values Between Steps
I'm new in Django and I.m trying to do a FormWizard. The example work but the when I move between steps(not submit) the form does not keep or retain the data already typed. How could I keep the data moving back and forward? --forms.py class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.CharField(required=False) class ContactForm3(forms.Form): message = forms.CharField(widget=forms.Textarea,required=False) -views.py class ContactWizard(SessionWizardView): template_name = "contact_form.html" def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response('done.html', {'form_data': form_data}) -
Why do I get the error, "350 is not JSON serializable"
I've been working on a project in Python using Matplotlib in tandem with Django. Right now I just want to display the graph in the webpage. Before, I saved the figure as a PNG, and the graph showed up. Unfortunately, this disables some interactive features that I had planned on including. In order to work around this, I used MPLD3's function, fig_to_html, which I saw worked in other examples. However, when I used the line in my own code, I got the error, "350 is not JSON serializable". Here is my code: def index(request): # template = loader.get_template('') noaaNmbr='11809' #for right now, this is the only active region that I'm pulling data for. When I get the graph up and running, I will make it more interactive for the user so that he can urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true" webUrl = urlopen(urlData) counter = 0 data = webUrl.read().decode('utf-8') hekJSON = json.loads(data) getInfo(counter, hekJSON) sort() # Sorts the data from earliest to most recent fig, ax = plt.subplots(figsize=(30, 30)) circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) # Creates circular representation of the sun on the graph because that's all I really need for now plt.plot(xcen, ycen, … -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. WHEN FULL in settings.py
Im having an issue getting my django up on a server. Here is the traceback. Traceback (most recent call last): File "manage.py", line 17, in <module> import AuShadha.startup as startup File "/home/vagrant/venv/AuShadha/src/AuShadha/AuShadha/startup.py", line 19, in <module> from AuShadha import settings File "/home/vagrant/venv/AuShadha/src/AuShadha/AuShadha/settings.py", line 8, in <module> django.setup() File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django /conf/__init__.py", line 116, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. and here is settings.py # Make this unique, and don't share it with anybody. SECRET_KEY = 'jbnlwhbvwdvilibbfwlhbwhbvccvjlanoajhfjdofffofoewfbwfho' This is also not my actual secret key -
Django How can I save two different class which are connected each other by OneToOne relationship in a form at once?
Let me explain what my problem is in more detail. First I have a class 'UserInfo' which connected to User class of django.contrib.auth.models like below models.py class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=15,blank=True,unique=True) position = models.CharField(max_length=15,blank=True,unique=True) class Meta: default_permissions = () def __str__(self): return self.position then I wanted to use ModelForm because I can write less codes. The reason why I made CreateNewUser class is that I wanted to let user can see only [username, email, groups, user_permissions] and control those. (to prevent them to select superuser or staff or inactive options) forms.py class CreateNewUserInfo(forms.ModelForm): class Meta: model = UserInfo fields = '__all__' class CreateNewUser(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'groups', 'user_permissions'] problem happened in here. I wanted to use FormView to use generic view with class typed view so that I can write less codes(concise code). there is attribute named 'form_class' and I couldn't put two different class with it. I wanted to put different two class to one form with generic view. views.py class TestView(FormView): form_class = CustomForm template_name = 'manager/alltoall.html' def form_valid(self, form): At the end, I made new class in forms.py and wrote every field which I need like below. … -
How to customize the list_display option in django using queryset?
I want to make a course guidance app for my college. Here is my model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Instructor(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User) # other stuff here def __str__(self): return self.name class Course(models.Model): course_code = models.CharField(max_length=10, default='CS') instructor = models.ForeignKey(Instructor) course_name = models.CharField(max_length=200) # other stuff here def __str__(self): return self.course_name class CourseOutline(models.Model): course = models.OneToOneField(Course) objectives = models.TextField(blank=True) # other stuff And this this my admin.py from django.contrib import admin from models import Course, CourseOutline, Instructor # Register your models here. admin.site.register(Instructor) class CourseAdmin(admin.ModelAdmin): # some other stuff def queryset(self, request): qs = super(CourseAdmin, self).queryset(request) if request.user.is_superuser: return qs # get instructor's "owner" return qs.filter(instructor__owner=request.user) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "instructor" and not request.user.is_superuser: kwargs["queryset"] = Instructor.objects.filter(owner=request.user) return db_field.formfield(**kwargs) return super(CourseAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) list_display = ('course_name', 'instructor') list_filter = ('queryset',) admin.site.register(Course, CourseAdmin) class CourseOutlineAdmin(admin.ModelAdmin): # nothing here of importance # whatever was here def queryset(self, request): qs = super(CourseOutlineAdmin, self).queryset(request) if request.user.is_superuser: return qs # get instructor's "owner" return qs.filter(course__instructor__owner=request.user) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "course" and not request.user.is_superuser: kwargs["queryset"] = Course.objects.filter(instructor__owner=request.user) return db_field.formfield(**kwargs) return super(CourseAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) … -
Django: Organize objects in a dictionary by foreign key
I have this problem: I've got two models, products and categories, the categories are defined in a fixture (they won't change), and I need to display all categories in a single template, as a grid. The models are rather simple, the important thing is that Products have a foreign key pointing to Category model, and another one pointing to User model (owner). I have to display all products in each category block (CSS doesn't matter, I just need to be able to bring them up) but the solution I've got so far is this View def index(request): user_products = [] if request.user.is_authenticated(): user_products = Product.objects.filter(owner=request.user) categories = Category.objects.all() return render(request, 'index.html', {'user_products': user_products, 'categories': categories}) Template <!-- This goes for each category, 12 in total --> <div> <h3>Category (name hardcoded)</h3> {% for category in categories %} {% if category.pk == 3 %} <ul class="product_list"> {% for product in category.product_set.all %} {% if product.owner == request.user %} <li> <div class="product"> <h2 class="title">{{ product.title }} </h2> <p class="text">{{ product.text }}</p> </div> </li> {% endif %} {% empty %} {% endfor %} </ul> {% endif %} {% endfor %} </div> I want send in context something like: user_products = {<category.pk>: [list of Product … -
Why is nothing showing up?
I've been working on a project in Python using Matplotlib in tandem with Django. Right now I just want to display the graph in the webpage. Before, I saved the figure as a PNG, and the graph showed up. Unfortunately, this disables some interactive features that I had planned on including. In order to work around this, I used MPLD3's function, fig_to_html, which I saw worked in other examples. However, when I used the line in my own code, nothing appeared on the screen. Here is my code: def index(request): # template = loader.get_template('') noaaNmbr='11809' #for right now, this is the only active region that I'm pulling data for. When I get the graph up and running, I will make it more interactive for the user so that he can urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true" webUrl = urlopen(urlData) counter = 0 data = webUrl.read().decode('utf-8') hekJSON = json.loads(data) getInfo(counter, hekJSON) sort() # Sorts the data from earliest to most recent chart = plt.figure() fig, ax = plt.subplots(figsize=(30, 30)) circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) # Creates circular representation of the sun on the graph because that's all I really need for now plt.plot(xcen, ycen, color="red") … -
Django How I can pass request.user(current logged user) in forms when I use class based view?
I wanted to pass request.user to show current user in a form with ModelMultipleChoiceField. I could figure out my problem thanks to here http://stackoverflow.com/a/25184373/6568309. I fixed my code like below. but I could get solution with only function based view. well, I kept using class based views because I could use generic views and it was recommended in first place. Is it way to pass request.user like below with class based view(to use FormView or ModelFormView)? Additionally, Is is normal to mix function based views and class based views to meet your need in Django? thank you in advance. forms.py class CustomForm(forms.Form): username = forms.CharField(initial='testname',max_length=150) email = forms.EmailField() phone_number = forms.CharField(max_length=15) position = forms.CharField(max_length=15) uperall = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(CustomForm, self).__init__(*args, **kwargs) self.fields['uperall'].queryset = User.objects.filter(username=user.username) urls.py urlpatterns = [ url(r'^$', UserList.as_view(), name='index'), url(r'^create/$', UserCreate.as_view(), name='create'), url(r'^test/$', TestView.as_view(), name='test'), url(r'^test1/$', views.ftestview, name='test1'), ] views.py def ftestview(request): if request.method == 'POST': form = CustomForm(request.POST, user=request.user) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] phone_number = form.cleaned_data['phone_number'] position = form.cleaned_data['position'] with transaction.atomic(): user = User.objects.create(username=username,email=email) userinfo = UserInfo.objects.create(user=user,phone=phone_number,position=position) userinfo.save() user.save() return HttpResponseRedirect('/success') else: form = CustomForm(user=request.user) return render(request, 'manager/alltoall.html', { 'form': form }) -
Django not connecting to MySQL properly, throws "ImportError: cannot import name 'NULL'"
I want to use Django (using Python 3) with MySQL. To do so, I installed mysqlclient. To first test the waters with MySQL, I also created a new Django project and app, changed the DATABASES configuration in "settings.py" to settings I prepared in MySQL, and ensured that MySQL server is running (the database I created for testing does not have any tables within it at this point). But when I do python manage.py runserver in terminal command, I get the following error: ImportError: No module named '_mysql_exceptions' ImportError: No module named '_mysql_exceptions' Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103efaea0> Traceback (most recent call last): File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/shtryts/Django-1.10.1/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/shtryts/Django-1.10.1/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/shtryts/Django-1.10.1/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/shtryts/Django-1.10.1/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/shtryts/Django-1.10.1/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File … -
Including filename parameter in Content-Disposition header (Request) - Django Rest Framework
I recently upgraded my Django version to 1.9 from 1.5, and in doing so, I seem to have run into an issue that I can't figure out how to resolve. I have DRF set up, that worked fine using Django 1.5 (DRF version was 2.3.14) The request is a POST request (multipart/form-data), that has several CharFields and of course a FileField. The error I'm getting now, which wasn't occurring before is: Here is my: models.py . . from __future__ import unicode_literals from django.db import models import datetime import pytz import os from uuid import uuid4 from django.utils.deconstruct import deconstructible #random file names plz - THIS HAD TO BE REFACTORED FOR DJANGO 1.9.7 @deconstructible class UploadAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.path, filename) upload_and_rename = UploadAndRename('tmp/youtube/') class Video(models.Model): video_id = models.CharField(max_length=25, null=True, blank=True) name = models.CharField(max_length=250) email = models.CharField(max_length=250) video_name = models.CharField(max_length=250) phone = models.CharField(max_length=25) institution = models.CharField(max_length=250, null=True, blank=True) categoryId = models.IntegerField(null=True, blank=True) city = models.CharField(max_length=250) provinceId = models.IntegerField(null=True, blank=True) age = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) language = models.CharField(max_length=2) file = models.FileField(upload_to=upload_and_rename, null=True) views.py ... from django.shortcuts import render from django.views.generic import TemplateView from django.conf import settings …