Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating / storing a form preview with Django forms and cart
I've never had to do this before and I'm wondering if I'm on the right track / this is the standard way to do something of this nature. I was going to use Django formtools FormPreview but it doesn' handle files (They can upload various images)... So, rolling my own solution or trying to. Currently I'm using a form wizard with model forms and everything validates / saves fine. I now want to add in a form preview, before purchasing the item they create with the form, and I've thought about doing the following: Save it to the database but mark it as not paid / inactive. On the form preview page grab the id (from pk in url) and display it. They have the option to go back and edit (update view) and / or pay. Using this route it's really easy to update and grab the data for viewing whether they wish to go back or forward. Similarly, if they add multiple items in their cart I can just display these items by grabbing the pk's from the DB rather than trying to handle a ton of session data. If they remove the item -> delete the row … -
Django UpdateView - get initial data from many-to-many field and add them when saving form
I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py: class MyModelUpdate(UpdateView): model = MyModel fields = ['m2m'] def get_initial(self): return initials def get_form(self, form_class=None): form = super(MyModelUpdate, self).get_form(form_class) form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user) return form def form_valid(self, form): form.instance.m2m.add( ??? add the initial values) return super(MyModelUpdate, self).form_valid(form) def get_success_url(self): ... -
django app deploy to google app engine
I am trying to deploy my django project on google app engine. When I 'gcloud app deploy' everything looks like it is going well except it takes a really long time. Then I get the message: 'ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section.' I checked my acitivity log in google cloud and i have the error: " STATIC_ADDRESSES quota limit reached " This is my first django project and first time on google app engine. How can I get this thing up? -
How to start building a django website with postgres nginx and gunicorn on separate machines?
I searched all over the internet and I guess I'm lost, Please I want a detailed answer here. I know how to make all three of these things(gunicorn, Nginx, and Postgres) work on the same machine but what if I wanna have all of them on the different/individual machine. Let's say I got 3 behemoth powerful machines capable of handling anything but the real question in my mind is where do I start. how can I connect all three of these together? what if I wanna add more storage? How do I connect multiple database machines together I'm sorry but I'm pretty new in networking and it's really crucial for me to understand this because if I don't my mind won't allow me to go ahead with the process. -
Error ! The following packages have unmet dependencies: mysql-server
I tried to install mysql on my ubuntu16.04 for a django project. The installation has some problem with some existing files, getting the error: mysql-server is already the newest version (5.7.19-0ubuntu0.16.04.1). You might want to run 'apt-get -f install' to correct these: The following packages have unmet dependencies: mysql-server : Depends: mysql-server-5.7 but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution) I tried, sudo apt-get -f install which gives error: Preparing to unpack .../mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb ... grep: /etc/mysql/: No such file or directory Aborting downgrade from (at least) 10.2 to 5.7. If are sure you want to downgrade to 5.7, remove the file /var/lib/mysql/debian-*.flag and try installing again. dpkg: error processing archive /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb (--unpack): subprocess new pre-installation script returned error exit status 1 Errors were encountered while processing: /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb E: Sub-process /usr/bin/dpkg returned an error code (1) I have tried installation steps also but gets the first error. -
Django crispy forms - creating a form in home.html and getting an error
I have built a crispy form from a tutorial (https://godjango.com/29-crispy-forms/) and am getting an error that I believe means I need to define a URL in the urls.py. I also get the sense that there may be more than one issue going on - I am still trying to make this work and will continue to research it but I am quite new to Django and Python so struggling on this. Any guidance gratefully received. Here's the error: Failed lookup for key [form] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x10faa03c8>, 'home_url': '/'}]" For reference here are the files: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions) class SimpleForm(forms.Form): username = forms.CharField(label="Username", required=True) password = forms.CharField( label="Password", required=True, widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember Me?") helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('login', 'login', css_class='btn-primary')) class CartForm(forms.Form): item = forms.CharField() quantity = forms.IntegerField(label="Qty") price = forms.DecimalField() helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( 'item', PrependedText('quantity', '#'), PrependedAppendedText('price', '$', '.00'), FormActions(Submit('login', 'login', css_class='btn-primary')) ) class CreditCardForm(forms.Form): fullname = forms.CharField(label="Full Name", required=True) card_number = forms.CharField(label="Card", required=True, max_length=16) expire = forms.DateField(label="Expire Date", input_formats=['%m/%y']) ccv … -
Error when running a Django server
I am using Django 1.8 and I get the following error: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middl eware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMi ddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. What do I have to do ? -
django domain setup and routing schema
Can anyone give me a short walkthrough (yes, I know that's asking a lot... I'm completely lost) of how to properly setup different domains using a single django project? Or... point me in the right direction / some insight to my questions below... I've searched around and looked at various app solutions, apache stuff, etc but still don't have a clear understanding. Specifically, each (main) app in my project is on a different domain. I have an app for news, job posts, etc and these would be on (name)news.io, (name)jobs.io, etc. In my settings.py file currently I'm using django-multiple-domains and have the MULTIURL_CONF set to point to each app based upon the domain name. As I understand it.... i can just set up the project on my domains using the same settings file since it will use this routing schema rather than the suggested route of multiple different settings file for each domain based upon the middleware that django-multiple-domains uses. Now, here's where I get confused on the URL routing.... In an app we typically include the urls inside the main urls.py file in the root app folder for our project to creating a routing schema for the entire site … -
How to create instances when there are multiple senders in django signals?
I am getting error order_id must be Order instance user must also be MyUser instance. How do i create instances? @receiver(post_save, sender=MyUser) @receiver(post_save, sender=Order) def create_order_message(sender, **kwargs): user_id = instance.id MyUser.object.filter(id=user_id) if kwargs.get('created', False): Notification.objects.create(order_id = kwargs.get('instance'), user = kwargs.get('instance'), title='Welcome to Django!', message='Thank for signing up!', ) -
Django with unique_together on foreign key and slug=slugify fails
I am building a basic CMS. I have created an organization app, that adds a project ID with foreign key to all my model objects. The form is for creating a basic website object with header and text. I was able to create and save one instance with the following code. Further tries with different titles fail with "(1062, "Duplicate entry '' for key 'cms_page_url_117a950602ffab5c_uniq'") I have now idea where I am going wrong, can somebody point me in the correct direction? I am running on mysql database. Model: class Page(models.Model): title = models.CharField(max_length=100) text = models.TextField(blank=True) slug = models.SlugField() date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(default=timezone.now) project = models.ForeignKey(Project) def __unicode__(self): return "Page '%s' @: %s from %s" % (self.title, self.slug, self.project) def __str__(self): return unicode(self).encode('utf-8') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Page, self).save(*args, **kwargs) class Meta: unique_together = (("project", "slug"),) Form: class PageForm(ModelForm): def __init__(self, *args, **kwargs): super(PageForm, self).__init__(*args, **kwargs) for key, field in six.iteritems(self.fields): field.widget.attrs['placeholder'] = field.label class Meta: model = Page fields = ['title', 'text'] # TODO: ordering title = forms.CharField(max_length=100, label=ugettext_lazy("Add a title")) text = forms.CharField(label=ugettext_lazy("Type your text here"), widget=forms.Textarea) def save(self, project, commit=True): instance = super(PageForm, self).save(commit=False) instance.project = project if commit: instance.save() return … -
django - making .create() support writable nested fields?
So in Django, .create() does not support writable nested fields. However, I have a nested field in my project. I looked at this question, which was helpful, but I'm now getting a ValueError at /transactions/ invalid literal for int() with base 10: 'Product001'. As far as I can tell, this is caused by the line in serializer.py that reads product = Product.objects.get(pk=validated_data.pop('sku')) specifically, the 'sku' value I have in there. My question is, what value should I put in there to replace 'sku'? The answer to the question I based my code on used 'event', but that's not part of my models in my project. I've also tried using 'product', and got a TypeError that sadi "int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict'". serializers.py from .models import Product, Family, Location, Transaction from rest_framework import serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('reference', 'title', 'description') class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('reference', 'title', 'description', 'unit', 'minQuantity') class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('sku', 'barcode', 'title', 'description', 'location', 'family') depth = 1 class TransactionSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Transaction fields = ('sku', 'barcode', … -
how to find much matches of one objects one queryset<==(which contain one finding object) in another queryset Django?
how to find many matches with one object from the set of queryset objects (which contain one search object) in another many queryset django objects for example, how to find the most frequent product in order products and deduce its quantity I apologize for such a question, I'm still noob and my brains can not so critical think i try to do this: product = Product.objects.all() some = Order.objects.filter(products_of_order__product__in=product).count() but it's just return all product which contain in order products, how to get count each product in orders products which matches with list of products. i have one idea how to make it but i wanna make it in one line) in one queryset) some_dict = {} for i in some: for s in i.products_of_order.all(): if s.product.name_of_product in some_dict: some_dict.s.product.name_of_product += 1 else: some_dict.s.product.name_of_product = 1 -
Django: IndexError: tuple index out of range on sending a JQuery POST request
I have a use case wherein I'm sending some data using POST request to a URL, which is mapped to a view which then returns a success status. JQuery $( "#submit-id-add-update-user-button" ).click(function() { first_name = $('input[name="first_name"]').val(); last_name = $('input[name="last_name"]').val(); age = $('input[name="age"]').val(); dob = $('input[name="dob"]').val(); place = $('input[name="location"]').val(); mobile = $('input[name="mobile"]').val(); email = $('input[name="email"]').val(); user_id = $('input[name="user_id"]').val(); new_user = (user_id == '') ? ('yes') : ('no'); var url = base_url + '/add-update-user/'; var data = { 'email': email, 'first_name': first_name, 'last_name': last_name, 'age': age, 'dob': dob, 'place': place, 'mobile': mobile, 'user_id': user_id, 'new_user': new_user, 'csrfmiddlewaretoken': csrftoken, }; $.post( url, data) .done(function( data ) { console.log('this is done'); window.location.href = "/"; }); }); urls.py url(r'^add-update-user/', add_update_user, name="add_update_user") views.py def add_update_user(request): return HttpResponse({'status':200}) However, this is the error that I'm encountering: Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 734, in format return fmt.format(record) File "/home/manas/Python/Interviews/pricebaba_env/local/lib/python2.7/site-packages/django/utils/log.py", line 173, in format if args[1][0] == '2': IndexError: tuple index out of range Logged from file basehttp.py, line 85 I'm not really sure what this error means or why is it arising. Would really appreciate some help on this. -
test django app with multiple domains locally
How would I go about testing a django app which uses multiple domains locally? Each app is on a different domain (i.e. - (somename)news.io, (somename)jobs.io, ...). I'm trying to test my url routing schema as well as session data being shared across the domains. I tried setting up apache, xampp, and using virtualhosts on windows but this didn't work for me - I couldn't figure out how to set up the virtualhosts (to fake the domains) and get my app served to them. So, looking for another route for testing. -
Sorting a table by clicking the table head column in Django Web
So I have a website in django. I have a table with a few colums like ServerName,IP etc.. I would like to have the header of the columns to sort the entire column. For example when I click the ServerName column it will order all the items by ABC order of the ServerName. I have heard of django-sorting-bootstrap but the guide seem complicated. Is there any easier or good guide to do that? the idea is to click with the arrow on the head and it will sort it out (It will be like a link). index.html table- <div class="container"> <br> <center><h1>DevOps Server List</h1></center> <br> <form method='GET' action=''> <input type='text' name='q' placeholder='Search Item'/> <input type='submit' value='Search' /> </form> <table class="table table-hover"> <thead> <tr> <th> Server Name </th> <th> Owner </th> <th> Project </th> <th> Description </th> <th> IP Address </th> <th> ILO </th> <th> Rack </th> <th> Status </th> <th> </th> </tr> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td>{{ server.ServerName }}</td> <td>{{ server.Owner }}</td> <td>{{ server.Project }}</td> <td>{{ server.Description }}</td> <td>{{ server.IP }}</td> <td>{{ server.ILO }}</td> <td>{{ server.Rack }}</td> <td>{{ server.Status }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#Del{{server.id}}">Delete <span class="glyphicon glyphicon-trash" </span></button> … -
Why Django serialize returns string
I have problem with returning something browsable form serializers.serialize. My model: class BowlingGame(models.Model): Frame = models.PositiveSmallIntegerField() FrameRow = models.PositiveSmallIntegerField() Result = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpare = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpareInfo = models.CharField(max_length=1, blank=True, null=True) Time = models.DateTimeField(blank=True, null=True) GameId = models.PositiveIntegerField() StateOfGame = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ('GameId',) def __str__(self): return str(self.GameId) And what I do next: >>> from django.core import serializers >>> from django.db.models import Max >>> from game.models import BowlingGame >>> a = BowlingGame.objects.all().aggregate(Max('GameId'))['GameId__max'] >>> game_frame = BowlingGame.objects.filter(GameId=a) >>> me = serializers.serialize('json', game_frame, fields=('Frame', 'FrameRow')) >>> me '[{"model": "game.bowlinggame", "pk": 2356, "fields": {"Frame": 1, "FrameRow": 1}}, {"model": "game.bowlinggame", "pk": 2357,......}}]' This seems to be string as >>> me[0] '[' and I'm looking for the first element of the queryset. I tried few more things: >>> me = serializers.serialize('json', [game_frame, ], fields=('Frame', 'FrameRow')) AttributeError: 'QuerySet' object has no attribute '_meta' My question: is it normal to return string? How I can browse the object. In fact I'm using it with AJAX but its the same. json.game_frame[0] returns '['. I need to be able to get the elements separately as normal dict or list. What is going on? -
How to add an option to view all (*) in Django?
I have a simple database with tables: Company 'CompanyID', 'int(10) unsigned', 'NO', 'PRI', NULL, 'auto_increment' 'CompanyName', 'varchar(70)', 'NO', '', NULL, '' 'Type', 'enum(\'C\',\'M\',\'S\',\'A\')', 'NO', 'MUL', NULL, '' 'Country', 'varchar(60)', 'YES', 'MUL', NULL, '' 'Website', 'varchar(60)', 'YES', '', NULL, '' 'Email', 'varchar(60)', 'YES', '', NULL, '' 'Telephone', 'double unsigned', 'YES', '', NULL, '' 'Maps_Link', 'varchar(60)', 'YES', '', NULL, '' CompanyDetails 'CompanyDetailsID', 'int(10) unsigned', 'NO', 'PRI', NULL, 'auto_increment' 'CompanyID', 'int(10) unsigned', 'NO', 'MUL', NULL, '' 'Type', 'enum(\'C\',\'M\',\'A\',\'S\')', 'NO', '', NULL, '' 'Category', 'enum(\'MEP Consultant\',\'Lighting Designer\',\'Architect\',\'Interior Designer\',\'MEP Contractor\',\'Fitout Contractor\',\'Procurement Company\',\'Developer\',\'Outdoor-Architectural\',\'Indoor-Architectural\',\'Indoor-Decorative\',\'Outdoor-Decorative\',\'Lamps\',\'Drivers\',\'Control Systems\',\'Landscaping Consultant\',\'Landscaping Contractor\',\'Other\')', 'NO', '', NULL, '' 'Comments', 'blob', 'YES', '', NULL, '' and 3 more tables (Contact, Continent, Product) I have created an app CompanyBrowser. I am trying to make a simple form with drop-down menus for: Type (from Company) Category (from Company Details) Country (from Company) For each of these, I want the user to have the option to select all (*) in the drop-down menu. Here is my urls.py: urlpatterns=[url(r'^$',views.Index,name='index'), url(r'^(?P<company_type>[CMSA*])/$',views.ResultsView.as_view(), name='results'), url(r'^(?P<company_type>[CMSA*])/(?P\<company_category>\w+)/$',views.ResultsView.as_view(), name='results'), url(r'^(?P<company_type>[CMSA*])/(?P<company_category>\w+)/(?P<company_country>\w+)/$',views.ResultsView.as_view(), name='results'), ]<br> Basically, I will be displaying according to url CompanyBrowser/company_type/company_category/company_country , where user can enter * i.e., all for any of the search field. This is the ResultsView I have coded so far: class … -
django admin edit model select/prefetch_related?
I have a Django website, with model Event, lets say: class Event(models.Model): home = models.ForeignKey('Team', related_name='%(class)s_home') away = models.ForeignKey('Team', related_name='%(class)s_away') ... class Team(models.Model): name = models.CharField("team's name", max_length=100) Using ForeignKeys for this was a bad idea, but anyway, how to make this usable in Django Admin page? In admin edit event page, a ton of foreign keys is fetched for this: http://127.0.0.1:8000/admin/event/event/116255/ It produces tons of selects like: SELECT "event_team"."id", "event_team"."name" FROM "event_team" WHERE "event_team"."id" = 346; and page dies. I was playing with these: class EventAdmin(admin.ModelAdmin): list_display = ('id', 'home', 'away', 'date_game', 'sport', 'result') search_fields = ['home__name', 'away__name'] list_select_related = ( 'home', 'away', 'league', 'sport', ... ) def get_queryset(self, request): return super(EventAdmin, self).get_queryset(request).select_related(*self.list_select_related) admin.site.register(Event, EventAdmin) But no luck. -
I want to use basic python modules for my django based website's back-end logic [on hold]
I want to use some of python's modules (especially audio and video modules) in my django based site's back-end processing. Is there any way to do it? Thanks -
How to send back the tokens to android using Firebase Auth
I am developing an Android app which uses Firebase and my own server running Django. What I intend to do is, I want to first authenticate the user using android app to the django server which then generates the custom tokens as specified in firebase docs. Then I want to send the generated custom token back to the android. My question is how to send that custom token back to android? I tried to send as JSON object. But it says JWT are not JSON serializable. I passed the username and password from android app as json object and authenticated with my django server. Here is my minimal Django code: import firebase_admin from firebase_admin import credentials from firebase_admin import auth cred = credentials.Certificate("firebase-admin.json") default_app = firebase_admin.initialize_app(cred) def validateuser(request): json_data=json.loads(request.body.decode('utf-8')) try: // I verify the username and password and extract the uid uid = 'some-uid' custom_token = auth.create_custom_token(uid) result={'TAG_SUCCESS': 1, 'CUSTOM_TOKEN': custom_token } except: result={'TAG_SUCCESS': 0, 'CUSTOM_TOKEN': '0'} return HttpResponse(json.dumps(result), content_type='application/json') But it says the custom token is not JSON serializable. Is it not the way to do like this? How do I send the custom token back to the android app? And this is the error: uid: 78b30d23-6238-4634-b2e4-73cc1f0f7486 custom_token: b'eyJraWQiOiAiZmFlNzA2MzZiY2UwZTk0Y2Y5YTM2OWRlNzc4ZDZlYWQ5NGMwM2MzYiIsICJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiZmlyZWJhc2UtYWRtaW5zZGstOXBtbjVAYnVzdHJhY2tlci0xZDE3OS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsICJ1aWQiOiAiNzhiMzBkMjMtNjIzOC00NjM0LWIyZTQtNzNjYzFmMGY3NDg2IiwgImF1ZCI6ICJodHRwczovL2lkZW50aXR5dG9vbGtpdC5nb29nbGVhcGlzLmNvbS9nb29nbGUuaWRlbnRpdHkuaWRlbnRpdHl0b29sa2l0LnYxLklkZW50aXR5VG9vbGtpdCIsICJleHAiOiAxNTA4MDc2OTA4LCAiaWF0IjogMTUwODA3MzMwOCwgInN1YiI6ICJmaXJlYmFzZS1hZG1pbnNkay05cG1uNUBidXN0cmFja2VyLTFkMTc5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0=.jgexW_xR5FeZvuO5TPWO8EOBnRJ28ut9OR_OxeajE1_o4ns4fwd2pMXlK2GkM464P5Vi-IxheG-IIJcANxGSDeZgvgpkLfKkHMZeSaraqfEQGq6N7ipuD8o1T7zd5qm79twmFbrQZRB1y7g1-zcjL69x8KFsThWOTmo0TYj5l3zf8_2Cxbw2SGefMWkCwL0d1yQjcUqVyuSAP3-Sg8KrrqCcG4cjNOXKeWxwbUQO7DobOQlT5TfRApwWk8Td6uPjD7d6jqMo-HPKOis0vRoXMBzflZKj36-hIOFkygZNbDWLTsQzbb3HZg8dBabA5GTy--iQi038TRMIm2W0irr0ng==' … -
django - TemplateDoesNotExist error
I am working through this Getting started with Django Rest Framework by Building a Simple Product Inventory Manager tutorial. At the end the tutorial, it says that I "should now be able to run your server and start playing with diffrent API endpoints". However, when I run the server, all I'm getting is a TemplateDoesNotExist error. At no point in the tutorial does it mention creating templates (and this is eventually going to connect to an Angular 2 frontend, as shown in this tutorial), so I'm confused at to whether this is an error in my code, or if the tutorial left a step out. I do not get any console errors when I run my code. serializers.py from .models import Product, Family, Location, Transaction from rest_framework import serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('reference', 'title', 'description') class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('reference', 'title', 'description', 'unit', 'minQuantity') class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('sku', 'barcode', 'title', 'description', 'location', 'family') depth = 1 class TransactionSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Transaction fields = ('sku', 'barcode', 'product') views.py from __future__ import unicode_literals from django.shortcuts import render from rest_framework import … -
How to set own icon fonts using ALDRYN_BOOTSTRAP3_ICONSETS in django-cms
How to set own icon fonts using ALDRYN_BOOTSTRAP3_ICONSETS in django-cms? We can read on https://github.com/aldryn/aldryn-bootstrap3 that it should be something like this: ALDRYN_BOOTSTRAP3_ICONSETS = [ ('glyphicons', 'glyphicons', 'Glyphicons'), ('fontawesome', 'fa', 'Font Awesome'), # custom iconsets have to be JSON ('{"iconClass": "icon", "iconClassFix": "icon-", "icons": [...]}', 'icon', 'Custom Font Icons'), ('{"svg": true, "spritePath": "sprites/icons.svg", "iconClass": "icon", "iconClassFix": "icon-", "icons": [...]}', 'icon', 'Custom SVG Icons'), ] but I dont know how to configure new iconset in my case icons from http://rhythm.nikadevs.com/content/icons-et-line Could someone help me with that? -
nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument ubuntu 16.04 xenial
I know this is a known bug, but i dont know how to resolve that because i do lot of googling and after that finally back to stack to get some real solution : Here are configuration: First i install nginx by: sudo apt-get install nginx lsb_release -rd Description: Ubuntu 16.04.2 LTS Release: 16.04 apt-cache policy nginx-core nginx-core: Installed: 1.10.3-0ubuntu0.16.04.2 Candidate: 1.10.3-0ubuntu0.16.04.2 Version table: *** 1.10.3-0ubuntu0.16.04.2 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-updates/main amd64 Packages 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-security/main amd64 Packages 100 /var/lib/dpkg /status 1.9.15-0ubuntu1 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial/main amd64 Packages My nginx service config is like: nano /lib/systemd/system/nginx.service # Stop dance for nginx # ======================= # # ExecStop sends SIGSTOP (graceful stop) to the nginx process. # If, after 5s (--retry QUIT/5) nginx is still running, systemd takes control # and sends SIGTERM (fast shutdown) to the main process. # After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends # SIGKILL to all the remaining processes in the process group (KillMode=mixed). # # nginx signals reference doc: # http://nginx.org/en/docs/control.html # [Unit] Description=A high performance web server and a reverse proxy server After=network.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;' ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;' ExecReload=/usr/sbin/nginx -g … -
Searching a few colums in Django
So I got a a Database with a few colums. I want to add to my search the option to search not only one column like Project. I want to search a few more colums too.. so the search will look for Project or ServerName or IP and search all of the colums or a few of them. Any idea? I tried (Project__icontains=query, ServerName__icontains=query) but it said wrong syntax. index.html- def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Project__icontains=query) else: posts = serverlist.objects.all() # else: models.py - from django.db import models class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) -
Django importing app models in non-app package
I have a django project with two apps, and I also want to have a scheduled job via Heroku's job scheduling tools which handles some regular database operations. In order to handle the tasks of the scheduled job, I have a separate package in my top-level django project folder. This package requires access to the models as defined in my apps. However, I cannot find out how to import the models from my apps. The structure is as follows: myproject | | myproject | | __init__.py | | ... | myapp1 | | __init__.py | | models.py | | ... | myapp2 | | __init__.py | | models.py | | ... | customjobmodule | | __init__.py | | ... | ... I have tried several ways of importing using sys.path.append() but none of them seem to work. They all say there is no module named myapp1.models import os import sys cwd = os.getcwd() sys.path.append(cwd + '/../myapp1/') from myapp1.models import Model1 ImportError: No module named myapp1.models Is there a way to do this? When searching around I have found plenty of information about using models between django apps, but not using them outside of the django framework altogether.