Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass variable as argument in Meta class in Django Form?
forms.py class MySelect(forms.Select): def __init__(self, *args, **kwargs): self.variations = kwargs.pop('variations') super(MySelect, self).__init__(*args, **kwargs) def render_option(self, selected_choices, option_value, option_label): return '<option whatever>...</option>' class CartItemForm(forms.ModelForm): class Meta: model = CartItem fields = ( 'variation', 'width', 'height', 'quantity', ) widgets = { 'variation': MySelect(variations=self.variation_query) } def __init__(self, *args, **kwargs): product = kwargs.pop('product') try: cart = kwargs.pop('cart') self.cart = cart except: pass super().__init__(*args, **kwargs) variation_field = self.fields['variation'] variation_field.queryset = Variation.objects.filter( product=product ) self.variation_query = Variation.objects.filter( product=product ) def save(self): cart_item = super().save(commit=False) cart_item.cart = self.cart cart_item.save() return cart_item Below is where you have to pay attention to. (in Meta class) widgets = { 'variation': MySelect(variations=self.variation_query) } self.variation_query is from __init__. How can I do this? -
I have tried to correct this Django Object set error but it has failed please help me out
from django.db import models class Gallery(models.Model): Title = models.CharField(max_length=250) Category = models.CharField(max_length=250) Gallery_logo = models.CharField(max_length=1000) def __str__(self): return self.Title + '_' + self.Gallery_logo class Picture (models.Model): Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) Title = models.CharField(max_length=250) Artist = models.CharField(max_length=250) Price = models.CharField(max_length=20) def __str__(self): return self.Title i keep getting this error Traceback (most recent call last): File "", line 1, in AttributeError: 'Gallery' object has no attribute 'pic_set' Am using Pycharm 2016 and i just begun self learning Django yesterday Thanks -
How to serialize multiple models with one Serializer using DjangoRestFramework?
I have these Models all of which have PointField: class Place(models.Model): title = models.CharField(max_length=75, verbose_name='Заголовок') category = models.ForeignKey(PlaceCategory, verbose_name='Категория') ... point = geomodels.PointField(geography=True, blank=True, null=True) ... class Event(models.Model): title = models.CharField(max_length=75, verbose_name='Заголовок') address = models.CharField(max_length=255, blank=True, null=True, verbose_name='Адрес') city = models.ForeignKey(City, verbose_name='Город') ... point = geomodels.PointField(blank=True, null=True) ... class Meeting(models.Model): title = models.CharField(max_length=75) participants = models.ManyToManyField(User, related_name='participating_meetings') ... point = geomodels.PointField(blank=True, null=True) ... In project I have /points API url. By this url I want to return filtered set or all the points to show them on map. I checked DRF documentation, there is example how to build Serializer for one Model, but how do I build the API view for these multiple models? -
If else logic in controller
I have four buttons. Below are their html, <label>Severity *</label> <button class="btn btn-default btn-lg" ng-click="sModal()" name="s" ng-model="cpform.severity">{{cpform.severity}}</button> <label>Occurence *</label> <button class="btn btn-default btn-lg" ng-click="OModal()" name="o" ng-model="cpform.occurence">{{cpform.occurence}}</button> <label>Detection *</label> <button class="btn btn-default btn-lg" ng-click="siverifydetectionModal()" name="detection" ng-model="cpform.detection">{{cpform.detection}}</button> <label>RPN</label> <button class="btn btn-default btn-lg" ng-model="cpform.risk_score">{{cpform.severity*cpform.occurence*cpform.detection}}</button> All these 4 buttons are displayed in the modal. The values for the first three buttons are got from different modals. Here, I have displayed the Product value in the last button in RPN. When I tried to save the value, I was able to save the values of first three buttons except the last button value. Below is my code in the controller part: $scope.cpform = { summary: r_header.summary, severity:r_header.severity, occurence:r_header.occurence, detection:r_header.detection, risk_score: r_header.risk_score, nocpz: nocpz_checked, route: r_header.route, layers: r_header.layers, comments: r_header.comments, risks: risk_id_list, }; } $scope.updateReview = function (cpform, formname) { $scope.uprev_submit_disabled = true; var updated_field_list = []; if (r_header.revSeverity[0] != null) { angular.forEach($scope.cpform, function(value, key) { //if(key[0] == '$') return; console.log("Chck", value, key); if (!formname[key].$pristine) { updated_field_list.push(key); } console.log("CPZ", key, formname[key].$pristine) }); I want to pass the Product Value which I get in the RPN button through the risk_score variable mentioned in the controller. I'm passing the $scope.cpform to the views and respectively to models in … -
How to set attribute in option tag element in django form?
I'm trying to set <option> attribute in Django form. What I'm trying to add is data-img-url, data-price, value: <select class="form-control" id="variation-select"> <option data-imgurl="/media/products/%EC%82%AC%EA%B3%BC/%EC%BB%AC%EB%9F%AC/1.png" data-price="60,000" value="multi"> 컬러 (60,000원) </option> <option data-imgurl="/media/products/%EC%82%AC%EA%B3%BC/%EB%8B%A8%EC%83%89/1.png" data-price="50,000" value="single"> 단색 (50,000원) </option> </select> Before I use django Form, I implemented like this: <select class="form-control" id="variation-select"> {% for variation in product.variation_set.all %} <option data-imgURL="{{ variation.variationimage_set.first.image.url }}" data-price= "{{ variation.price }}" value="{{ variation.color }}"> {{ variation.get_color_display }} ({{ variation.price }}원) </option> {% endfor %} </select> But I started to use Django Form and have in trouble when giving attribute to <option> tag. I found similar questions in stackoveflow, http://stackoverflow.com/a/6478841/3595632 http://stackoverflow.com/a/5090548/3595632 But problem is that I set attribute with django template tag... Here is the code: forms.py class CartItemForm(forms.ModelForm): class Meta: model = CartItem fields = ( 'variation', 'width', 'height', 'quantity', ) def __init__(self, *args, **kwargs): product = kwargs.pop('product') try: cart = kwargs.pop('cart') self.cart = cart except: pass super().__init__(*args, **kwargs) # 얘가 여기에 있어야 self.fields가 생성이 된다. variation_field = self.fields['variation'] variation_field.queryset = Variation.objects.filter( product=product ) models.py class CartItem(models.Model): cart = models.ForeignKey("Cart") variation = models.ForeignKey(Variation) # 벽화 너비 width = models.PositiveIntegerField( default=1, validators=[MinValueValidator(1)], ) class Product(TimeStampedModel): name = models.CharField(max_length=120, unique=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=400, blank=True) is_active = models.BooleanField(default=True) … -
List field input in django rest frameowrk browsable api - mongoengine
I have created a serializer that takes a list argument tags, but on the django-rest-framework browsable api, It doesn't seem to work. Code: Model class SocialFeed(Document): platform = StringField(max_length=20, required=True, choices=('facebook', 'twitter', 'instagram')) tags = ListField(default=None) created_at = DateTimeField(default=datetime.now(), required=True) Serializer class SocialFeedCreateSerializer(DocumentSerializer): class Meta: model = SocialFeed fields = [ 'id', 'platform', 'tags' ] View class SocialFeedCreateAPIView(CreateAPIView): queryset = SocialFeed.objects.all() serializer_class = SocialFeedCreateSerializer But on the browsable API, It shows a simple input box to enter tags, and I don't know what format should I put the tags in on the browsable API side, and I am not receving list of tags instead a string. If anybody has faced the same issue, please guide me. -
Django rest framework gis-leaflet plotting and cordinates
I am using django restframework gis and using geofeaturemodel serializer to generate geojson response.But the co-ordinates i am getting seems to wrong in some other projection system(assuming projected coordinate system).Can we convert that coordinate system into geometric coordinate system in the rest framework gis so that in the frontend it can be plotted using leaflet library { "type": "Feature", "geometry": { "type": "MultiPoint", "coordinates": [ [ 2048157.72954293, 765203.671727644 ] ] }, "bbox": [ 2048157.72954293, 765203.671727644, 2048157.72954293, 765203.671727644 ], "properties": { "autogenera": 40, "name": "111A-CB", "networknam": "PROP STORM POND EAST", "rimelevati": 367.464470905157, "partsizena": "48 x 48 Rect Structure 24 x 36 Frm" } } -
Django support static file for production
In my settings.py, STATIC_ROOT = '/home/khantthulinn/webapps/static_media/' STATIC_URL = '/home/khantthulinn/webapps/static_media/' In my urls.py, urlpatterns = patterns('', url(r'^admin/', admin.site.urls), #Media (r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT}), )+ static(settings.STATIC_ROOT, document_root=settings.STATIC_ROOT) After that, in my web server, I have copied static files. python manage.py collectstatic Everything is okay and I see all correctly. It become problem when I change DEBUG = False. I read this already but I don't understand. https://docs.djangoproject.com/en/1.10/howto/static-files/deployment/ I have read solution from here too. Why does DEBUG=False setting make my django Static Files Access fail? With debug turned off Django won't handle static files for you any more - your production web server (Apache or something) should take care of that. I wana try that. How shall I do? I don't want to run this since it is insecure. manage.py runserver --insecure -
Django REST calling reversed detail route cannot find kwargs
I'm implementing 'users/me/'. (I alse read the the article, but I'm try to add some specific function) I made a function in UserViewSet: @list_route() def me(self, request): # ... find user ... request.path = reverse('user-detail', kwargs={'pk': user.id}) self.partial_update(request) It raises AssertionError: Expected view UserViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. print(request.path) is /users/2/, so reverse is working. urls.py: router = routers.DefaultRouter() router.register(r'users', UserViewSet, base_name='user') How could I deliver a pk? I have no idea what is the mistake I made. -
Django SlugField versus URLField
Both of these fields appear to serve essentially the same purpose. What are the situations in which you might choose one over the other? -
Can a MagicMock object be iterated over?
What I would like to do is this... x = MagicMock() x.iter_values = [1, 2, 3] for i in x: i.method() I am trying to write a unit test for this function but I am unsure about how to go about mocking all of the methods called without calling some external resource... def wiktionary_lookup(self): """Looks up the word in wiktionary with urllib2, only to be used for inputting data""" wiktionary_page = urllib2.urlopen( "http://%s.wiktionary.org/wiki/%s" % (self.language.wiktionary_prefix, self.name)) wiktionary_page = fromstring(wiktionary_page.read()) definitions = wiktionary_page.xpath("//h3/following-sibling::ol/li") print definitions.text_content() defs_list = [] for i in definitions: print i i = i.text_content() i = i.split('\n') for j in i: # Takes out an annoying "[quotations]" in the end of the string, sometimes. j = re.sub(ur'\u2003\[quotations \u25bc\]', '', j) if len(j) > 0: defs_list.append(j) return defs_list -
Within Dango, how do I add a new value to request.POST data before saving?
I'm trying to allow the user to either manually enter a text field if they have the license info, or let it auto generate (based on form info) if its original content. I'm stuck because from my tests (using print command) the form is correctly updating with the information given in the form if LicenseTag field is left blank. The issue is that the updated information is not being saved in the database. After research this seems to be an issue of immutability, which is why I added request.POST.copy() and tested the commented out section defining mutability=True. Here's my views.py def STLupload(request): if request.method == 'POST': form = NewUpload(request.POST, request.FILES) data = request.POST.copy() if form.is_valid(): #Dis gona need alot of work firstname = request.user.first_name lastname = request.user.last_name displayname = request.user.display_name email = request.user.email if (firstname or lastname == "None"): if displayname == "None": liscname = email else: liscname = '%s %s' % (firstname, lastname) else: liscname = displayname filetitle = request.POST.get( 'Title' , '') lisc = '%s %s' % (filetitle, liscname) if data['LicenseTag'] == "": ''' mutable = request.POST._mutable request.POST._mutable = True request.POST['LicenseTag'] = lisc request.POST._mutable = mutable ''' data['LicenseTag'] = lisc print (request.POST.get( 'LicenseTag' , '')) print ("blank") else: … -
How to transfer data from Django to Ext JS
I'm new to web programming. I would like to create a simple Django application with Ext JS interface. Task: The user enters data into a database using forms and sees the database upgrade.It has been done to solve the problem as follows. Written Django application. views.py def addProduct(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): data = form.cleaned_data product_name = data['product_name'] product_price = data['product_price'] Products.objects.create(name=product_name, price=product_price) else: form = ProductForm() return render(request, 'addProduct.html', { 'ProductsList': Products.objects.all(), 'form': form, # 'Title': 'Range of products', # 'product_name': 'type product name here', }) template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ Title }}</title> </head> <body> <table> <tr> <th>Name</th> <th>Product</th> </tr> {% for current in ProductsList %} <tr> <td>{{ current.name }}</td> <td>{{ current.price }}</td> </tr> {% endfor %} </table> <form action="check/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="ADD" /> </form> </body> </html> forms.py class ProductForm(forms.Form): product_name = forms.CharField(max_length=100) product_price = forms.IntegerField() models.py class Products(models.Model): name = models.CharField(max_length=30) price = models.IntegerField() This works well. Now I would like to use Ext.grid.Panel component from Ext JS to render table. Question: How do I transfer data from Django to Ext JS? -
Django: extending models of other apps
I'm working on small ERP-like project on Django which contains different apps (Products, Sales, Purchases, Accounting, MRP, ...). A few of them are "base-level", while others have dependencies (for example, a Sales app requires the Products app). For the sake of modularity and loose-coupling, I'm trying to keep the apps as independent as possible: those with dependencies aren't allowed to modify the underlying data. However, it would be extremely useful and make things way simpler if the apps could extend (add fields) tables in the models of their dependencies (for instance, Sales would add a can_be_sold BooleanField in one of the tables within the scope of Products). This way when a user internally chooses to install an app, a setup function makes the required "upgrades" for it to integrate properly with the dependencies, while the user installs only what he needs without having to provide unnecessary or unrelated information. I thought of making one-to-one relationships with the dependencies, but this solution doesn't convince me because (a) it doesn't seem very efficient to make so many new tables for maybe one or two extra fields, and (b) working with forms and signals would be a hassle (making code harder to mantain … -
Difficulty Implementing TinyMCE for Form Fields
I have been unsuccessful in getting an implementation of TinyMCE to work for me. I'm relatively new to Django, so I think I'm missing something simple. Any help would be greatly appreciated! For now, I'm just trying to get the WYSIWYG editor to show up in the form template. I've moved the TinyMCE static files to '/static_in_env/static_root/js/tiny_mce/' Here are the relevant contents of some of my files: settings.py: INSTALLED_APPS = [ # 'screener.apps.ScreenerConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party 'tinymce', # my apps 'blog', 'screener', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env', 'static_drop'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_in_env', 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static_in_env', 'media_root') # TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, 'js/tiny_mce') TINYMCE_JS_ROOT = 'js/tiny_mce' TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, 'tiny_mce.js') urls.py: from django.conf.urls import url, include from . import views app_name = 'screener' urlpatterns = [ url(r'^tinymce/', include('tinymce.urls')), url(r'^(?P<ticker>[A-Z]+)/notes/$', views.CompanyNotesView.as_view(), name='company-notes', ), ... ] widgets.py: from django import forms from django.conf import settings from django.utils.safestring import mark_safe class AdvancedEditor(forms.Textarea): class Media: js = ('js/tiny_mce/tiny_mce.js',) def __init__(self, language=None, attrs=None): self.language = language or settings.LANGUAGE_CODE[:2] self.attrs = {'class': 'advancededitor'} if attrs: self.attrs.update(attrs) super(AdvancedEditor, self).__init__(attrs) def render(self, name, value, attrs=None): rendered = super(AdvancedEditor, self).render(name, value, attrs) return rendered + … -
Add new row after specified number of columns added javascript
I've been working in getting a dashboard with buttons, each button will represent one machine. This buttons are generated depending on the Jquery results. Currently, I would like to have 10 buttons added in one row, and then to continue adding them in a new row. Also, my other issue is that I want to change the button color depending on the result of the ajax. I've tried the following code, but it is giving me as a result the image that I've attached below. IMAGE: http://i68.tinypic.com/296oysw.png (Sorry, couldn't post the image since I'm new to Stackoverflow) $( document ).ready(function(){ var d = new Date(); var now = d.getTime() + 300; var color; var u = '/read/machines/' +{{userid}}; $.ajax({ url: u, type: "GET", dataType: 'json', success: function(data) { $.each(data, function(i, item) { if (item.lastCommunication > now ){ color = "success"; }else{ color = "warning"; } if (i != 0 && i%10 == 0){ $('<tr>').append( $('<td>').append( $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') ) ).appendTo('#body'); }else{ $('<td>').append( $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') ).appendTo('#body'); } }); } }); }); </script> -
Apache 2.4 with mod_wsgi: Internal Server Error with wsgi.py
I am trying to deploy my django project on a windows server, using apache 2.4 with mod_wsgi and pythong 3.4. Now when I could run apache just fine but I got Internal Server Error when going to localhost, I have this Internal Server Error. Then I looked at the error.log and found the following: The 'Apache2.4' service is restarting. The 'Apache2.4' service has restarted. winnt:notice] [pid 7756:tid 528] AH00424: Parent: Received restart signal -- Restarting the server. [Thu Sep 29 18:18:19.003503 2016] [wsgi:warn] [pid 7756:tid 528] mod_wsgi: Compiled for Python/3.4.2. [Thu Sep 29 18:18:19.003503 2016] [wsgi:warn] [pid 7756:tid 528] mod_wsgi: Runtime using Python/3.4.3. [Thu Sep 29 18:18:19.003503 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00455: Apache/2.4.23 (Win64) mod_wsgi/4.4.12 Python/3.4.3 configured -- resuming normal operations [Thu Sep 29 18:18:19.003503 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00456: Apache Lounge VC10 Server built: Jul 9 2016 11:59:00 [Thu Sep 29 18:18:19.003503 2016] [core:notice] [pid 7756:tid 528] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Thu Sep 29 18:18:19.003503 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00418: Parent: Created child process 10400 [Thu Sep 29 18:18:19.347246 2016] [wsgi:warn] [pid 10400:tid 456] mod_wsgi: Compiled for Python/3.4.2. [Thu Sep 29 18:18:19.347246 2016] [wsgi:warn] [pid 10400:tid 456] mod_wsgi: Runtime using Python/3.4.3. [Thu Sep 29 … -
Python Django, access to function value through urls?
how can I get the value of "otro" function ?, this code works but it only show me the value of get function, how can get the value of otro? I do not understand how to do it un the urls. views: from django.views.generic import ListView, View from . models import Autor from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect def inicio(request): return HttpResponse('HOLA') # Create your views here. class MiVista(View): def get(self, request): # <la logica de la vista> return HttpResponse('resultado') def otro(self, request): # <la logica de la vista> return HttpResponse('otro') urls: from django.conf.urls import url, include from django.contrib import admin from .import views from .views import MiVista urlpatterns = [ url(r'^hola$', views.inicio), url(r'^indice/', MiVista.as_view()), ] Thank you ! -
Django capture url with "%20" and redirect
I'm not good at regexes. I need to redirect a url that looks like this: http://www.example.com/files/BIENES%20INMUEBLES%20DISPONIBLES.pdf?39 How can I capture it with a url pattern? I tried this: url(r'^files/BIENES%20INMUEBLES%20DISPONIBLES.pdf?39$', views.MyRedirectView.as_view()), But it doesn't work, I get a 404. How can I solve this? -
openstack horizon karma testing error
Here is karma testing log 29 09 2016 23:52:27.891:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#iQUnK4CCCLTiDBeVAAAA with id 4153563 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.accordion_nav.68aa89626bfa.js:1 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.accordion_nav.js:1 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.communication.4b05e1211ea9.js:8 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.communication.js:8 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.d3barchart.9be765d96dc3.js:79 PhantomJS 2.1.1 (Linux 0.0.0) ERROR ReferenceError: Can't find variable: horizon at /vagrant/src/ce_thysa/static/horizon/js/horizon.d3barchart.js:79 Unhandled rejection Error: Not running at Server.close (net.js:1237:11) at /vagrant/src/ce_thysa/node_modules/karma/lib/server.js:345:17 at tryCatcher (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/util.js:26:23) at Promise._settlePromiseFromHandler (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:510:31) at Promise._settlePromiseAt (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:584:18) at Promise._settlePromises (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:700:14) at Async._drainQueue (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:123:16) at Async._drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:133:10) at Async.drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:15:14) at process._tickCallback (node.js:458:13) Unhandled rejection Error: Not running at Server.close (net.js:1237:11) at /vagrant/src/ce_thysa/node_modules/karma/lib/server.js:345:17 at tryCatcher (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/util.js:26:23) at Promise._settlePromiseFromHandler (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:510:31) at Promise._settlePromiseAt (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:584:18) at Promise._settlePromises (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:700:14) at Async._drainQueue (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:123:16) at Async._drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:133:10) at Async.drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:15:14) at process._tickCallback (node.js:458:13) Unhandled rejection Error: Not running at Server.close (net.js:1237:11) at /vagrant/src/ce_thysa/node_modules/karma/lib/server.js:345:17 at tryCatcher (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/util.js:26:23) at Promise._settlePromiseFromHandler (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:510:31) at Promise._settlePromiseAt (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:584:18) at Promise._settlePromises (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/promise.js:700:14) at Async._drainQueue (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:123:16) at Async._drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:133:10) at Async.drainQueues (/vagrant/src/ce_thysa/node_modules/karma/node_modules/bluebird/js/main/async.js:15:14) at process._tickCallback (node.js:458:13) Unhandled rejection Error: Not running at … -
Django - get_or_create() with auto_now=True
I’m using Django and I'm having a problem with a Python script that uses Django models The script that I'm using takes data from an api and loads it into my database. my model: class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=True, blank=True) release = models.DateField(null=True, blank=True) poster = models.TextField(max_length=500, null=True) runtime = models.IntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) edit = models.DateTimeField(auto_now=True, null=True, blank=True) the script: movies = tmdb.Movies().upcoming() results = movies['results'] ids = [] for movie in results: data, created = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path'], popularity=movie['popularity']) The problem I'm having is that whenever I run the script, the entries are duplicated because the edit field is change, but the purpose I put the edit field is to know when exactly a movie got edited, ie: some other field got changed. How can I avoid the duplicates, but also keep the edit field in case some real change happened? -
How can I update two models in one serializer in Django Rest Framework?
I have a database schema that has each object of a certain type being stored across two separate tables (one row in each table, different data in each, with a foreign key from one to the other.) Unfortunately, Django Rest Framework tends to assume that there is a one to one correspondence between serializers and models, which is not true of my case. How should I be approaching this? It seems like the serializer should return the representation of the object which will be the actual HTTP response of the ajax requests, so using two serializers doesn't seem right. I've looked at extending BaseSerializer (which is how I currently plan to implement this if I don't find better solutions), but certain methods take in an instance, which should contain all the data needed to serialize the object, whereas I have two instances relevant. Any advice would be super appreciated! Thank you. -
Django - How to Modularize a large web Application?
I'm trying to figure out the best way to build a large web application, but keeping the various logical sections modularized. For example, there will be a number of different logical sections: Estimates Work Orders Accounting Contacts etc... As much as possible, I want to have the code for each of these modules disconnected from all the other modules. If code from one section starts to throw errors or cause incorrect data, I don't want that to affect other modules. My first thought is just to separate by using Django 'apps'. Each module is its own app. Then, if I build each app to be "pluggable", then the code is self sufficient. However, the problem with this approach is that the modules will likely need to access the models of other modules. For example, the 'Accounting' module will need access to the 'Contacts' model, since we want to send invoices to people in our contacts list. I looked into having a completely separate Django project for each module, but that poses problems (I think) for user authentication. Plus, to my knowledge, multiple Django projects can't (easily) share one database. Just wondering if there are any good ways or best practices … -
Some Safari users get "Safari Can't Open the Page" on the first load
I've noticed that some of my users randmonly get "Safari Can't Open the Page" the very first time they load our application, which gets automatically fixed if they reload. Testing with a user with the problem, I found that it doesn't happen on Chrome or Firefox. Another oddity is that some links work, but others that have more functionality in them (auto-login from link, etc) will fail. The internet says that it could be a DNS issue, but that doesn't explain why Chrome works. What could be the culprit? We don't even have KeepAlive on as our load balancers handle that part and they're set to 60 seconds over there. -
Django. Access the foreign key fields in the template from a form object
I use Django 1.8.14. I have two models: class Event(models.Model): title = models.CharField(max_length=255,) date = models.DateTimeField() ... def __unicode__(self): return self.title class Card(models.Model): user = models.ForeignKey(MyUser, related_name="user") event = models.ForeignKey(Event,) ... Card model form: class CardForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CardForm, self).__init__(*args, **kwargs) self.fields['event'].empty_label = None class Meta: model = Card fields = ('event', ) widgets = {'event': forms.RadioSelect, } I render form like this: <form method="POST"> {% csrf_token %} {% for choice in cardform.event %} {{ choice.tag }} {{ choice.choice_label }} {% endfor %} </form > In the label of each radio button I need to display both fields value "title" and "date" of Event model which is ForeignKey of Card. Now label includes only "title" value. What is the best way to do it? I tried {{ cardform.instance.event.date }} but it doesn't work.