Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is possible for Django to upload file without FORMS?
Im currently working with a custom html template not using forms on my django app to upload an img in a specific path. models.py class Document(models.Model): doc_file = models.FileField(upload_to='app/img/') views.py def app_save(request): if request.method == 'POST': newdoc = Document(doc_file=request.FILES.get('myfile')) newdoc.save() app_template.html <form id="myform" method="POST" action="{% url 'my_app:save' %} enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit"> </form> Result After submitting the form i dont have any internal server error and no python traceback. But there was no image uploaded in the app/img path and in my database i have blank record inserted because of newdoc.save() query. It is possible to work with file managing without forms? -
AttributeError: 'Response' object has no attribute '_closable_objects'
I'm trying to implement redis cache system in my website. So I need to change my cache settings from django LocMemCache to redisCache, CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '/var/run/redis/redis.sock', }, } and also want to include two middleware in settings. django.middleware.cache.UpdateCacheMiddleware django.middleware.cache.FetchFromCacheMiddleware Now I'm getting the attribute error from django 'Response' object has no attribute '_closable_objects'. And all the previously working API's returns internal server error. Any way redis cache is working fine for me. Please help me to find out why this issue occurs. -
Django multiple admin site with different base_site.html
I'd like to have multiple admin sites with different base templates for each site. One can create admin/base_site.html and add that path to TEMPLATE_DIRS in the front so that the base_site.html takes precedence. But it overrides the multiple admin sites. Is there a way to customize each admin site? -
Django DRF: Default URL always gets trigered first instead of route.url
I have a very simple Django Rest Framework application, my urls.py looks like the following router = routers.DefaultRouter() router.register(r'activity-list', activities.views.ArticleViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls, namespace='api')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Base/default URL, when all else fails urlpatterns += [ url(r'', TemplateView.as_view(template_name='index.html')), ] When I run the url http://127.0.0.1:8000/api/activity-list, the route that comes from the DRF router never gets reached. The server always seems to give precedence to the default URL, and index.html is always rendered. However, if I change the Default URL to: # Base/default URL, when all else fails urlpatterns += [ url(r'BLABLABLA', TemplateView.as_view(template_name='index.html')), ] Only then are the DRF routes reachable. This is what makes me think it's a precedence issue. The DRF routes are working, they just always get beaten by the default URL. I've tried variants suggested in the DRF docs, without luck, such as : But the same thing keeps happening. How can I make my DRF routes reachable while maintaining a default route for the server to land on? -
Cannot download file in Django
I am trying to figure out how to download files in Django.I went through a couple of answers on stackoverflow and tried out this: views.py def download(): file = open("DemoCSV.csv", "r") response = HttpResponse(file,content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="DemoCSV.csv"' return response The file DemoCSV.csv is in the same folder as my app. When I hit the url from the browser,I cannot download the file.This error message is shown: TypeError at /resources/download_files download() takes 0 positional arguments but 1 was given What am I missing? -
Why won't my Angular front-end pass correct $http.get parameters to Django back-end?
I have a Web Application made up of front-end client written in Angular/Javascript and a back-end server written in Python/Django. I'm trying to do a simple http GET request from the client to the server and it is not working. The reason it is failing is because for some unknown reason, the parameters are not being passed correctly. Here is the line of code being called on my client: $http.get(API + '/api/getProfile', {'profileId':5}).then(console.log('A'), console.log('B')); And here are the relevant lines of code on my server: class GetProfileAPI(views.APIView): def get(self, request, *args, **kwargs): logger.info("request.get_full_path() = %s" % request.get_full_path()) profile_id_arg = request.GET.get('profileId') logger.info("profile_id_arg = %s (%s)" % (profile_id_arg, type(profile_id_arg))) # Do something here if profile_id_arg is not None. When I run this code, I expect profile_id_arg on the server side to be the string 5. But instead look at the output that I get: request.get_full_path() = /api/getProfile profile_id_arg = None (<type 'NoneType'>) Why isn't profile_id being received properly and how can I fix this? Code example would be helpful. -
materialize modal select not displaying
I have a Django form rendering in a modal. The name field works fine but the 2 select fields are showing options even when they have their active class on. <div id="modal1" class="modal"> <div class="modal-content"> <h4>Create a Store</h4> <form action="/" method="post"> {% csrf_token%} {% for field in form %} <div class="input-field"> {{ field.errors }} {{ field.label_tag }} <br>{{ field }} </div> {% endfor %} <button class="btn" type="submit">Create!</button> </form> </div> <div class="modal-footer"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> Script at bottom $(document).ready(function(){ $('.modal-trigger').leanModal(); $('select').material_select(); }); the model Form class StoreForm(forms.Form): name = forms.CharField(required=True) store_size = forms.ChoiceField(widget=forms.Select(), choices=models.SIZE_CHOICES, initial='1', required=True) subscriber_status = forms.ChoiceField(widget=forms.Select(), choices=models.SUBSCRIBER_LEVEL, initial='1', help_text="You can always downgrade or upgrade through your console") class Meta: model = models.Store For extra clarity, what the inspector looks like on the element <div class="select-wrapper"><span class="caret">▼</span> <input type="text" class="select-dropdown" readonly="true" data-activates="select-options-2de779c1-46cd-3271-5da4-889766247340" value="Silver"><select id="id_subscriber_status" name="subscriber_status" class="initialized"> <option value="-1">Inactive</option> <option value="0">Free</option> <option value="1" selected="selected">Silver</option> <option value="2">Gold</option> <option value="3">Platinum</option> </select></div> No idea why readonly is true, as i've not set it to be so. I've fiddled with every attr in the console and tried adding styles like z-index and overflow and still nothing. Thanks -
Django - Can't load static file (404 error)
I'm developing web with django framework. So I have 3 folders in my static file like this. *web *home *static *admin *scripts *styles *web *manage.py *db.sqlite3 and I have my setting file with this static setup BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) But when I type python3 manage.py collectstaitc I get this result Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/pwanhsu/django/django/core/management/__init__.py", line 349, in execute_from_command_line utility.execute() File "/Users/pwanhsu/django/django/core/management/__init__.py", line 341, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/pwanhsu/django/django/core/management/base.py", line 290, in run_from_argv self.execute(*args, **cmd_options) File "/Users/pwanhsu/django/django/core/management/base.py", line 341, in execute output = self.handle(*args, **options) File "/Users/pwanhsu/django/django/contrib/staticfiles/management/commands/collectstatic.py", line 176, in handle collected = self.collect() File "/Users/pwanhsu/django/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect for path, storage in finder.list(self.ignore_patterns): File "/Users/pwanhsu/django/django/contrib/staticfiles/finders.py", line 112, in list for path in utils.get_files(storage, ignore_patterns): File "/Users/pwanhsu/django/django/contrib/staticfiles/utils.py", line 28, in get_files directories, files = storage.listdir(location) File "/Users/pwanhsu/django/django/core/files/storage.py", line 286, in listdir for entry in os.listdir(path): FileNotFoundError: [Errno 2] No such file or directory: '/Users/pwanhsu/Desktop/v_bridge/web/web/static' I can successfuly collect static file if I remove the STATICFILES_DIRS like this # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT … -
Why Django by default add `_id` suffix to the db column name of a foreign key?
I'm designing a Django style ORM. If you use user = models.ForeignKey(User), Django will convert it to user_id to database. Why not just use a column name without _id suffix? I've checked several similar questions but none satisfied me. It is better that the name of a model field consistents with its database column name , isn't it? -
how to include tests in a distributable django app?
I distribute a small django app that I wanted to write a test for. It uses some settings and I was importing from django.conf import settings in the app file but this leaves me with a problem because the standalone app has no django project so how would one write and run tests on it? -
Fetch models from raw PostgreSQL query using GraphQL for Django (Graphene)
What is the best way to use GraphQL with Django when using an external database to fetch data from multiple tables (i.e., creating a Django Model to represent the data would not correspond to a single table in my database). My approach was to temporarily abandon using Django models since I don't think I fully understand them yet. (I'm completely new to Django as well as GraphQL.) I've set up a simple project with an app with a connected external Postgres DB. I followed all the setup from the Graphene Django tutorial and then hit a road block when I realized the model I created was an amalgam of several tables. I have a query that sends back the proper columns mapped to the fields in my model, but I don't know how to make this a dynamic connection such that when my API is hit, it queries my database and maps the rows to the model schema I've defined in Django. My approach since has been to avoid models and use the simpler method demonstrated in Steven Luscher's talk: Zero to GraphQL in 30 Minutes. The goal is to be able to hit my GraphQL endpoint, use a cursor … -
using Markup on Django Template
i found this code in this question: Plotting graph using python and dispaying it using HTML from plotly.offline import plot from plotly.graph_objs import Scatter ...other imports.... @app.route('/results', methods=['GET', 'POST']) def results(): error = None if request.method == 'POST': my_plot_div = plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], output_type='div') return render_template('results.html', div_placeholder=Markup(my_plot_div) ) # If user tries to get to page directly, redirect to submission page elif request.method == "GET": return redirect(url_for('submission', error=error)) i'm trying to using it, to embed a plotly graph on my django template. But i always get this error... enter image description here Exception Value: global name 'Markup' is not defined i just install: pip install django-markup and put it in my installed_apps but i don't know if i have to import it in views.py. or if anyone knows another way to send the DIV of the graph, because when i try to use a dictionary, i get The name of the file is too long -
Celery with SQS sending message but not executing task
I've configured celery to call to SQS and when I check the queue on the AWS console the message count increases. However the tasks themselves do not run, I see some errors in /var/log/celery-worker.log that gives off this: [2016-09-08 01:24:24,940: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 26.00 seconds... [2016-09-08 01:24:50,960: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 28.00 seconds... [2016-09-08 01:25:18,997: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 30.00 seconds... [2016-09-08 01:25:49,030: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 32.00 seconds... [2016-09-08 01:26:21,069: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 32.00 seconds... [2016-09-08 01:26:53,111: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 32.00 seconds... I'm confused, the broker is contacting SQS properly, so why is it not activating the task, the worker is running locally on the same machine. This is all an elasticbeanstalk instance using django. -
How do i programmatically logout user?[Django]
I know to logout user in Django. If i want to logout user, i would do from django.contrib.auth import logout def logout_view(request): logout(request) But what is the relevant way of logging out the user if i am using django oauth toolkit(DOT)? Should i follow the same or delete the token? Some says delete the token and some says expiry period should be expired. Please provide me the best possible resolution for logging out in DRF using DOT. -
ionic/angularjs with django csrf works on local server but not working on device
I am working on ionic and use the Django( with rest framework) as backend. I tried to post to my server with $http as following: $http({ url: url, method: method, data: { // some data } }).success...... Also I set the following in my config: $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; I also tried ngCookies but $cookies.csrftoken does not return anything. Here is my backend code: class Mark(APIView): def post(self, request): // do something return Response({ //something }) This works perfect when I used ionic local server(ionic serve), but when I built it on ios emulator or on my iphone, csrf 403 appears: {"detail":"CSRF Failed: CSRF token missing or incorrect."} returned from the server. Any idea on this? Thank you so much! -
How to update a HyperlinkedRelatedField in Django Rest Framework
I'm trying to update a HyperlinkedRelatedField connected to a ManyToManyField in Django through Django Rest Framework and coming up with a successful PUT (status 200) that ignores my HyperlinkedRelatedField data. I'm obviously missing something, but what? #models.py class Product(models.Model): name = models.CharField(_('Name'),) number = models.IntegerField(_('Number'),) slug = models.SlugField(_('Slug'),) class UserPrefs(models.Model): other_prefs = models.CharField(_('Other Prefs')) favorite_products = models.ManyToManyField( Product, blank = True) #views.py class UserPrefsViewSet(viewsets.ModelViewSet): permission_classes = ( permissions.IsAuthenticated, ) serializer_class = UserPrefsSerializer def get_queryset(self): user = self.request.user return UserPrefs.objects.filter(user=user) #serializers.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ( 'url', 'name', 'number', 'slug', ) extra_kwargs = { 'url': {'lookup_field': 'slug'} } class UserPrefsSerializer(serializers.HyperlinkedModelSerializer): favorite_products = serializers.HyperlinkedRelatedField( queryset = Product.objects.all(), many = True, read_only = False, view_name = 'product-detail', lookup_field = 'slug',) class Meta: model = UserPrefs fields = ( 'url', 'other_prefs', 'favorite_products', ) For example, using httpie from the command line, my PUT: http -a my_auth_details PUT http://localhost/api_v2/userprefs/1/ {favorite_products: ['http://localhost/api_v2/product/jacket/', 'http://localhost/api_v2/product/shirt/']} ...and the result: HTTP/1.0 200 OK { "favorite_products": [], "url": "http://localhost:8000/api_v2/userprefs/1/" } -
ValueError - didn't return response object - returned None
I know views are required to return a response (not None) and I think I have all my logic tests covered. The second render (in case of POST) is not nested under the form.is_valid test with the intent of the post simply failing silently. Need some outside eyes. def listClients(request, list_type): if request.method == 'GET': # Create Form Object form = PostNotes() return render(request, 'dashboard/displayclientlist.html', { 'form': form, }) else: form = PostNotes(request.POST) if form.is_valid(): note = form.save(commit=False) note.notedate = timezone.now().date() note.cliendid_id = id note.trainer = request.user.username note.save() # Create Form Object form = PostNotes() return render(request, 'dashboard/displayclientlist.html', { 'form': form, }) Am I missing something obvious here? I have removed extraneous code (assigning other variables for template tags that are not relevant to the form. Can include (but left out for brevity). As always your eyes, suggestions and help is always appreciated. Cheers! -
create django many to many without unique key
I have a many to many table created by django with "cart/item" relationship. I would like to have multiple of the same item per cart, but django creates a unique key which doesn't allow this. here are my entities: class Sku(models.Model): product = models.ForeignKey(Product) size = models.IntegerField(choices=SIZE_CHOICES) price = models.DecimalField(max_digits=8, decimal_places=2) default = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.product.name class Cart(models.Model): customer = models.ForeignKey(Customer, blank=True, null=True) skus = models.ManyToManyField(Sku) purchased = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) How can I bypass this unique or I am fighting the framework? -
Software development houses in the Atlanta, GA, Savannah, GA, Charleston, SC, or Jacksonville, FL areas
I need some help with job hunting research. Here's my deal: I want to begin a career developing software. I am an aerospace engineer by training who has become disillusioned with working in that discipline and want to do software development instead. Over the past two years I have gone back to school and done post-bacc studies in computer science and law. I have experience with Java SE and Java EE for academic projects and have spent time on my own learning both Python, Ruby, and PHP. I have also recently learned about the Django web framework, which would be a nice area to get work in. What I need is to start networking and possibly do an internship at a local software development house. Does anyone out there know of software firms in the Atlanta, Savannah, Charleston or Jacksonville areas which take on neophytes for internships? Thanks -
Bitnami Django Stack not working with React
I have deployed a Django application using Bitnami's Django Stack application. In my application, I'm using React for some of my views and loading them into my Django template via {% load render_bundle from webpack_loader %}. However, when trying to access my website, the browser stalls and nothing is loaded (I assume that the webpack_loader has something to do with it. Any tips for debugging or does anyone have a solution? Thanks. -
Docker compose run migrations on django web application + postgres db
Hi I am having issues running migrations on postgres db container from django. Here is my docker-compose file web: restart: always build: ./web expose: - "8000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static env_file: - ./.env environment: - DEBUG=1 command: /usr/local/bin/gunicorn mysite.wsgi:application -w 2 -b :8000 nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - web links: - web:web postgres: restart: always build: ./postgres env_file: .env ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ The directory structure is below. The .env file defines the Postgres DB , user name and password DB_NAME=test DB_USER=test DB_PASS=test! DB_SERVICE=postgres DB_PORT=5432 POSTGRES_USER=test POSTGRES_DB=test POSTGRES_PASSWORD=test! When I run docker-compose build and docker-compose up -d nginx, postgres and web containers start. The postgres startup (default) creates the db, user and password. The django startup container installs requirements.txt and starts the django server (everything looks good). On running makemigrations docker-compose run web /usr/local/bin/python manage.py makemigrations polls I get the following output Migrations for 'polls': 0001_initial.py: - Create model Choice - Create model Question - Add field question to choice But when I run docker-compose run web /usr/local/bin/python manage.py showmigrations polls the output is. polls (no migrations) on running docker-compose run web /usr/local/bin/python manage.py migrate --fake … -
Django Annotate- Grouping with multiple .annotate() functions
I have the following manager, which is working correctly. def by_customer_and_date(self, start_date, end_date): qs = self.model.objects.filter( date__range=(start_date, end_date) ).values( "customer__name" ).annotate( grand_total_cogs=Sum('total_cogs'), total_sales=Sum('value'), total_profit=Sum('profit'), total_kgs=Sum('qty_applied'), current_balance=Sum('sale__receiptallocation__qty_applied') ).order_by('-total_kgs') Results are properly grouped by customer name by using .values("customer__name") However, what I'd like to do is this: def by_customer_and_date(self, start_date, end_date): qs = self.model.objects.filter( date__range=(start_date, end_date) ).values( "customer__name" ).annotate( grand_total_cogs=Sum('total_cogs'), total_sales=Sum('value'), total_profit=Sum('profit'), total_kgs=Sum('qty_applied'), current_balance=Sum('sale__receiptallocation__qty_applied') ).annotate( margin=Case( When(total_sales=0, then=0), default=(F('profit')) / (F('value'))*100 ) ).order_by('-total_kgs') I am using the annotated values to calculate another value whose denominator may be zero (hence the use of Case(When)). When I add this portion, the .values("customer__name") function loses it's effect, and each individual item is shown. I've tried moving the .values("customer__name") portion to the end (with added explicit references to each field name), but the issue remains. Is this the intended behavior? Is there any way to work around it? -
django-carton: how to access Cart in view?
so I am using this carton as a way to maintain a user selection of items. It has been working all fine when I display the content of this cart by doing: {% for item in cart.items %} {{ item.equipment.asset_number }} {% endfor %} in template and this gave me the asset number of those equipment in cart, works fine. However, now I am trying to access the Cart in view.py and tried something like this: for item in Cart.items_serializable: cart_list.append(item.equipment.id) and this gave me TypeError at /calbase/export/custom 'property' object is not iterable This is not covered in documentation and I can't seem to figure it out from the source code. Please help! Traceback: File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hansong.li\Documents\GitHub\frontEndCal\calbase\views.py" in export_data 183. for item in Cart.items_serializable: Exception Type: TypeError at /calbase/export/custom Exception Value: 'property' object is not iterable my slightly modified cart.py: from decimal import Decimal from django.conf import settings from carton import module_loading from carton import settings as carton_settings from calbase.models import Equipment class CartItem(object): """ A cart item, with the associated product, its quantity … -
Sending SMS from django app
I came to the requirement to send SMS from my django app. Its a dashboard from multiple clients, and each client will have the ability to send programable SMS. Is this achievable with django smsish? I have found some packages that aren't updated, and I sending email sms is not possible. All answers found are old and I have tried all approaches suggested. Do I have to use services like twilio mandatorily? Thanks -
How to get user_url part being at site.com/user_url/gallery/slug in case of DetailView?
I want to get link in template from site.com/user_url/gallery/slug back to site.com/user_url/gallery/ using something like: <a href="{% url 'profiles_user:profiles_gallery' -->>>????<<<--- %}" class="btn btn-default">"Come back to all galleries and photos"</a> Where instead of -->>>????<<<--- I need to provide user_url argument in order to get such url as site.com/user_url/gallery. # site.com/user_url/gallery/slug - gallery details class ProfileGalleryDetailView(DetailView): template_name = 'profiles/gallery_detail.html' def get_queryset(self): print(self.__dict__) user = get_object_or_404(UserProfile, user_url=self.kwargs['user_url']) return Gallery.objects.filter(galleryextended__user=user, slug=self.kwargs['slug']).on_site().is_public() print(self.__dict__) shows me: {'args': (), 'kwargs': {'slug': 'time-sleep', 'user_url': '1-plus-1'}, 'request': <WSGIRequest: GET '/1-plus-1/gallery/time-sleep/'>, 'head': <bound method BaseDetailView.get of <profiles.views.ProfileGalleryDetailView object at 0x7fe912b41860>>} How can I get 'user_url': '1-plus-1' from kwargs in template? Do I need to use get_context_data in order to add user_url to context? # Core urls.py urlpatterns = [ url(r'^(?P<user_url>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')), ] # profiles.urls urlpatterns = [ url(r'^$', views.ProfileDetailView.as_view(), name='profiles_home'), url(r'^gallery/$', views.ProfileGalleryArchiveIndexView.as_view(), name='profiles_gallery'), url(r'^gallery/(?P<slug>[\-\w]+)/$', views.ProfileGalleryDetailView.as_view(), name='profiles_gallery-details'), ]