w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
DISTINCT keyword IN MYSQL backend in Django?
try shared_file = File.objects.filter(id__in = Share.objects.filter(user_id = log_id) .values_list('file', flat=True)) .annotate(count=Count('share__shared_user_id', distinct=True))

Categories : Mysql

customise form-fields of django-registration utilising the simple.backend
models.py from registration.signals import user_registered from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, primary_key=True, related_name="user") # Extra attributes bio = models.TextField(null=True) country = models.ForeignKey(Countries, null=True) @receiver(user_registered) def registration_active_country(sender, user, request, **kwargs): print >> sys.stderr , request.POST['country'] funid = request.POST['country'] a = Countries.objects.get(pk=funid) userid = user.id user = UserProfile.objects.get(pk=userid) user.country = a user.save() urls.py url(r'^accounts/register/$', register, {'backend': 'registration.backends.simple.SimpleBackend','form_class': UserRegistrat

Categories : Django

django distinct doesn't return just unique fields
As Rob pointed out, distinct() works differently than you expected. It looks at all the fields to determine uniqueness, not just the ones you specify in values(). If you're using PostgreSQL then you can do what you want by passing arguments to distinct(). From the documentation: You can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. This translates to a SELECT DISTINCT ON SQL query. Here’s the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names. Getting back to your ultimate goal of finding all conversation partners, I don't

Categories : Django

Best way to show two fields of one related object in ModelAdmin
It's unclear what you're asking. Do you need something different from the default Django model admin as documented here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-objects Edit: In that case, you'll want to modify the form used in the modeladmin, probably the easiest way to do this is with modeladmin.get_form() and then formfield_overrides to change the widget. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides

Categories : Django

Android SQLLite, Syntax error when trying to get data from single database column
you are using db.query in wrong way Cursor cursor = db.query(DATABASE_TABLE, new String[]{KEY_MAKE}, null, null, null); should be equal to SELECT KEY_MAKE FROM DATABASE_TABLE if you want to filter the table, use the third parameter for the where clause String whereClause = "id=? AND group_id=?"; String[] args = new String[]{"1", "2"}; //some example data Cursor cursor = db.query(DATABASE_TABLE, new String[]{KEY_MAKE}, whereClause, args, null);

Categories : Java

Django ModelAdmin extra input field not from Model
EquipmentAdmin is not a model. Your ModelForm needs to reference Equipment from django import forms from django.contrib import admin from flightdeck.models import Equipment class EquipmentAdminForm(forms.ModelForm): reason = forms.CharField() class Meta: model = Equipment PS: when you have circular references, there are many ways around the problem. The best way with model imports and django is to use django.db.models.get_model('app', 'model')

Categories : Python

Django aggregation across multiple tables in ModelAdmin queryset
If you want to stay within Django's queryset, I would consider creating a model superclass that shares the related and common fields and sub-classing for further distinctions. Otherwise, you need to either write custom SQL or get out of the database ORM entirely and manipulate your data in python with Queryset.values or Queryset.values_list

Categories : Python

Default django-ajax-uploader with s3 backend gives MalformedXML error
I solved this problem with a custom s3 backend that override the upload function & use django-storages instead of boto to save files. try this : from ajaxuploader.backends.base import AbstractUploadBackend from django.core.files.storage import default_storage class S3CustomUpload(AbstractUploadBackend): NUM_PARALLEL_PROCESSES = 4 def upload_chunk(self, chunk): #save file to s3 self._fd.write(chunk) self._fd.close() def setup(self, filename): self._fd = default_storage.open('%s/%s' % ('uploads/materials/', str(filename)), 'wb') def upload(self, uploaded, filename, raw_data, *args, **kwargs): try: if raw_data: # File was uploaded via ajax, and is streaming in. chunk = uploaded.read(se

Categories : Python

Synchronize Postgres Server Database to Sqllite Client database
There is no one size fits all approach here. You need to carefully consider exactly what needs to be done, what you are replicating, how much data is involved, and what your write models are, all before you build a solution. Along the way you have to decide how to handle write conflicts and more. In general the one thing I would say is that such synchronization works best with append-only write models (i.e. inserts, no deletes, no updates), and one way to do it is to log changes that need to be made and replicate those changes. However, master-master replication is difficult on the best of days and with the best of tools available. Jumping between databases with very different capabilities will introduce a number of additional problems. You are in for a big job.

Categories : Sqlite

Add sqllite column to an existing database or have database re-index upon delete
According to SQLite's manual here you can re-index your auto id field by deleting its entry in the sqlite_sequence table like this: delete from sqlite_sequence where name='<Your Table Name Here>'; I haven't done this myself but it should work. Edit It is not clear in the SQLite's manual that the entry of your table will be re-created whenever a new insertion happens, however it clearly states that you can update the sqlite_sequence. So if the deletion doesn't solve your problem you can try to update the index like this: update sqlite_sequence set seq = 0 where name='<Your Table Name Here>'; Hope this helps...

Categories : Android

how to populate database fields when model changes in django
You can add your code in migration script created by south. If you have updated a model and done schemamigration with south, it will create a script to apply that migration. It will be in appname/migration/00N_some_name.py. You can add your code in forwards() method in that script at the end after schema alteration is done.

Categories : Mysql

CakePHP 1.3 Return all fields but with one of the fields as DISTINCT
$this->Car->find('first', array('conditions'=>array('Car.colour'=>'blue'))); This will return the result that you trying to get. I'm afraid this is not what you expected :)

Categories : Cakephp

Upgrading sqllite database schema
EDIT: Overlooked your instance call, you're definetely missing getWritableDatabase() before writing to the Database AND while we're at it, change your TABLE_ROW_ID contstant value to "_id" when working with cursors...should work now. String newTableQueryString = "create table if not exists " + TABLE_NAME + " (" + TABLE_ROW_ID + " integer primary key autoincrement not null, " + TABLE_ROW_ONE + " text, " + TABLE_ROW_TWO + " text, " + TABLE_ROW_THREE + " text, " + TABLE_ROW_FOUR + " text, " + TABLE_ROW_FIVE + " text);"; That's how i would do

Categories : Android

Why is this field not being updated in the SQLLite database?
Looks like you are reading same values for both _url and _remoteHomeDir from the edittext siteManHome. This can be a mistake and may be you have separate edit texts in the GUi That is: _url = siteManHome.getText().toString(); _remoteHomeDir = siteManHome.getText().toString(); Maybe you meant to get _remoteHomeDir from a different field?

Categories : Java

I am wondering how my app accesses SQLLite database in ios App
By default, if you are only giving the name of the file when opening your database, it is stored on your device. Each device has its own "sandbox" on your device where its files get stored. If you want to save your data to the cloud, that requires additional programming. Here is a good description in Apple's documentation. Here is a description on how to use the cloud.

Categories : Iphone

How do i create a new row in a database table in django with a submit button and innerHTML names as the data fields?
If I understand your question right: If you want to use django.forms to validate your posted data, you need to give the HTML form input fields unique names. Since the data you want to post are not in HTML input fields, I suggest you use javascript to extract the values and post via AJAX, like jQuery.post().

Categories : Django

Fetch Image From Sqllite Database in iphone
i think you are getting bytes in string type in [[arra objectAtIndex:0] valueForKey:@"ImageName"]; so first get string and then convert it to data. try like this: NSData* data = [[[arra objectAtIndex:0] valueForKey:@"ImageName"] dataUsingEncoding:NSUTF8StringEncoding];

Categories : IOS

How to save Sql Image retrieved through web service on IOS Sqllite database
In theory you are not doing anything wrong, so try to get the key and value before you pass then on setValue:forKey:, and check if they already exists. NSString *key = [keys objectAtIndex:i]; NSData *data = [rowData GetValue:key]; However, I recommend setting the property directly instead of using setValue:forKey: in this case, and further, it's much better to save the images on disk, and persist the respective paths on CoreData (assuming you are using it based on the classes and methods on your sample code).

Categories : IOS

Application force close while loading from sqllite database
From your log: no such table: gps: , while compiling: select * FROM gps WHERE type="Agence". Be sure you have it and built before. In OpenHelper class you have method onCreate where actually you generate your table. @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE gps ....... } From your code we don't see how did you build it. BTW, its not a big problem to create table if you haven't, no worries, but by this way you can prevent above mentioned errors.

Categories : Android

format a time textview in a Sqllite database Listview
Sort It. This helped alot Changing values from Cursor using SimpleCursorAdapter Final code public void PopulateListViewFromDatabase() { Cursor cursor = myDb.getAllRows(); startManagingCursor(cursor); // Setup mapping from the cursor to view fields String[] fromFieldNames = new String[] { DBAdapter.KEY_START, DBAdapter.KEY_FINISH, DBAdapter.KEY_ACTIONHRCOUNT, DBAdapter.KEY_BANGCOUNT, DBAdapter.KEY_RANDOMOPT }; int[] to=new int [] { R.id.txtStartTime, R.id.txtFinishTime, R.id.txtActionCount, R.id.txtBangCount, R.id.checkRandom }; //Create adap

Categories : Android

sqllite 3.7.17 compilation error under FreeBSD
Yasir is right in that you should be using the ports of all of the already-ported software you need. If you aren't administrating the server yourself, you ought to be able to ask the admin(s) to install the databases/sqlite3 port for you. Back to your actual question, it is difficult to know, why the fchmod is not declared in your case -- it is declared in <sys/stat.h>. Perhaps, you are using Makefile generated on one platform (Linux?) to build sqlite on a different platform (FreeBSD)? You should not do that -- configure needs to run locally. But, again, do not build it yourself...

Categories : Sqlite

BWDB SQLLite wrapper Release error
Both __unsafe_unretained and __weak prevent the retention of objects, but in slightly different ways. For __weak, the pointer to an object will convert to nil on the deallocation of the object it points to, which is very safe behavior. As its name implies, __unsafe_unretained will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object. In BWDB example there is a row stored to an instance variable enumRows in enumerating function - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained *)stackbuf count:(NSUInteger)len { if ((*enumRows = [self getPreparedRow])) { state->itemsPtr = enumRows; state->state = 0; // not used

Categories : Objective C

PhoneGap with Django Backend
That's right, you cannot run python code on iOS or Android using PhoneGap, but there is no need to do that. Yes, you can build a native mobile application of your site using PhoneGap. I'll try to explain a bit how these technologies compare to each other: Django is a python web framework running on a web server PhoneGap is a framework for building native mobile applications using web technologies (HTML5+CSS+Javascript), the application will run on a mobile device One common approach is to build the mobile UI with i.e. jQuery Mobile and use the Django web application to provide a RESTful API to get data to the application. Take a look at this another question for more details. Edit: Answer the question in the first comment Yes, it's possible to build a fast and well working applic

Categories : IOS

Modularization of Backend (Django)
As a beginner you better stick with different projects for different domain, when you gain more experience, you will find out how much of the logic is reused in both and then make a decision of reusing the apps in single project. Please read the section on wsgi: https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/

Categories : Django

I have a Django ModelForm with added fields and field limitations. Not all fields are showing
If You use fields in Meta then You must list expliticly all fields that You want to use, even the ones You are adding to the form, but are not present in the model. What do You mean by that You can't change the fields in Meta? Can You change the __init__ function on the form? You can also subclass this form and override fields or __init__.

Categories : Python

Using memcached with a dynamic django backend
You would cache whatever is being most frequently accessed from your Database. Make a list of the most frequent requests to get data from the database and cache the data in that priority. Cache the most frequent requests based on category of the pictures Cache based on users - power users go into cache (those which do a lot of data access) Cache the most recent inserts (in case you have a page which shows the recently added posts/pictures) I am sure you can come up with more scenarios. I am positive memcached (or any other caching) will help, even though your app is very 'dynamic'.

Categories : Django

Django forms which fields are required as "bound" fields to validate
Based on your clarifying comment: [T]here is some data, but the form is still form.is_bound=False. What I want to know is what more I need to add to the data in order for is_bound to be True. It's not a question of what data is present or absent, it's a question of how you construct the form object. From the docs: To create an unbound Form instance, simply instantiate the class: >>> f = ContactForm() To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor: >>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data) That is, if you provided an argument when instantiating the form, it's bound. If n

Categories : Django

Get distinct sets of fields from MongoDB
it is not that easy, but you can do it :-). The most challenge is to create the bson query and to use the runCommand syntax from mongodb. Here is some example code and the data you can find in docs.mongodb.org. An example SQL query could look like this: SELECT state, SUM(pop) AS totalPop FROM zips GROUP BY state HAVING pop > (10000) In mongoDB shell you will run something like this. db.zipcodes.aggregate( { $group : { _id : "$state", totalPop : { $sum : "$pop" } } }, { $match : {totalPop : { $gte : 10000 } } } ) You can run the same with the command db.runCommand which has the following default syntax for the aggregation framework: db.runCommand( { aggregate :

Categories : R

django-balanced - Database Error
You need to set the DJANGO_SETTINGS_MODULE: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

Categories : Mysql

database error no such table django
The main difference is that firing manage.py sql myapphere will show the queries used to create the schema for your database, while the ouput of myapp.objects.all() will simply return a list of the entries in that database. For example, if you had a list of articles, the manage.py sql command would show the myapp properties while myapp.objects.all() will show the instances of myapp in the database. To further extrapolate your problem, try opening up your DB client and make sure the column names match the ones described in your model. If they don't match up, you might need to drop the table and resync your database (I definitely had that problem).

Categories : Django

Which backend for caching results from API calls in Django
As you mentionned it, the results are long lived, so why not save the results to disk as a text file containing the JSON once it has been made for the first time ? I had a similar issue with some API calls extracting huge amounts of data. This is how I solved my problem: Hash the query string (search=noodles => 838f8d9a[..]a370bbfa6df46b171c02f0c) Search for the file with the same hash (838f8d9a[..]a370bbfa6df46b171c02f0c.txt) If the file exists: Check the file creation time (see How to get file creation & modification date/times in Python?) If the file is recent enough, just send the contents of the file as the response. If the file doesn't exist: Generate the contents (as you're doing now) and save the contents in a file (with the hash of the query as filename for future r

Categories : Django

Good Program example Mongodb backend with Django 1.3
Well MongoDB provides an Online shell to test and see MongoDB working you can test some code snippets there and it is much JSON like code, so that would be easy to grasp http://www.mongodb.org/ (there would be an option called try it out) and learn also The below link might help you. http://mongoengine-odm.readthedocs.org/en/latest/django.html

Categories : Django

Django custom backend Session Timeout
At settings: SESSION_EXPIRE_AT_BROWSER_CLOSE = False This middleware will check for max 24h + 1h idle: class timeOutMiddleware(object): def process_request(self, request): shouldLogout = False if request.user.is_authenticated(): if 'beginSession' in request.session: elapsedTime = datetime.datetime.now() - request.session['beginSession'] if elapsedTime.seconds > 24*3600: del request.session['beginSession'] shouldLogout = True else: request.session['beginSession'] = datetime.datetime.now() if 'lastRequest' in request.session: elapsedTime = datetime.datetime.now() -

Categories : Django

Django Multiple Authentication Backend for one project, HOW?
You can have multiple authentication backends. Just set the AUTHENTICATION_BACKENDS in settings.py of your Django project to list the backend implementations you want to use. For example I often use a combination of OpenID authentication and the standard Django authentication, like this in my settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'django_openid_auth.auth.OpenIDBackend', ) In this example Django will first try to authenticate using django.contrib.auth.backends.ModelBackend, which is the default backend of Django. If that fails, then it moves on to the next backend, django_openid_auth.auth.OpenIDBackend. Note that your custom backends must be at a path visible by Django. In this example I have to add django_openid_auth to INSTAL

Categories : Python

How do I configure Simple Backend in Django Registration
The code... url(r'^accounts/register/$', RegistrationView.as_view(success_url=settings.LOGIN_REDIRECT_URL), name='registration_register') ...is technically correct, but it looks like there's a bug in the django-registration library which means it will effectively ignore this value, so you'll have to override the get_success_url() method if you actually want something that works.

Categories : Python

Change Django Authentication Backend for Testing
Create an alternative settings file, for example myproj/test_settings.py, and specify that settings file when running unit tests. Write the alternative settings file like this: from myproj.settings import * AUTHENTICATION_BACKENDS = ( #'your.ldap.backend', 'django.contrib.auth.backends.ModelBackend', ) That is, the settings inherits everything from your regular settings, but overrides the AUTHENTICATION_BACKENDS definition, with your LDAP backend commented out. Then, run your tests like this: python manage.py test --settings=myproj.test_settings

Categories : Django

How to make some django form fields depend on the value of other fields?
form.clean is the right place to do this. What's not right is calling clean_<field> for other fields - they will have already been cleaned and their values will be in the cleaned_data dict. Take a look at the example in the docs: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other It runs through almost exactly this scenario, showing how you can test one field based on another and how you can either raise a form-level error when missing or bind the error to one of the fields.

Categories : Django

Select fields from table with DISTINCT field
Use GROUP BY before the order clause and if you want order results first then group them then use subselect SELECT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd FROM my_table GROUP BY `user` ORDER BY (parentsEd + sonsEd) DESC SELECT DISTINCT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd FROM my_table ORDER BY (parentsEd + sonsEd) DESC SELECT a.* FROM ( SELECT DISTINCT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd FROM my_table ORDER BY (parentsEd + sonsEd) DESC ) a GROUP BY a.`user`

Categories : Mysql

MongoDB Aggregation: Counting distinct fields
I figured this out by using the $addToSet and $unwind operators. Mongodb Aggregation count array/set size db.collection.aggregate([ { $group: { _id: { account: '$account' }, vendors: { $addToSet: '$vendor'} } }, { $unwind:"$vendors" }, { $group: { _id: "$_id", vendorCount: { $sum:1} } } ]); Hope it helps someone

Categories : Mongodb

How To Select Distinct Row Based On Multiple Fields
WITH CTE AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY Owner ORDER BY Date DESC) AS RN FROM tablename ) SELECT ID, Name, Date, Location, Owner FROM CTE WHERE RN = 1;

Categories : SQL



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.