Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access related object after save
I need to get Question after Answer is saved. class Answer(models.Model): # ... def save(self, *args, **kwargs): super(Answer, self).save(*args, **kwargs) # I need to get question object here q = self.question.get() And Question class Question(models.Model): # ... answer = models.ForeignKey(Answer, related_name='question', blank=True, null=True) They are related through a foreign key. If I try answer.question.get() I get that it doesn't exist. If I try to get Question by answer_id it doesn't find anything either as if question wasn't updated yet (but I can get it later). Any ideas? -
Python class variable is set in init, but then not defined in save
I have a Django form, in which I set the value of a variable in the __init__ method, and then try to save it in the save method. However, when I load the webpage in my browser, the console indicates that the variable is not defined when I try to use it in the save method: class abcForm(ValidatedForm): ... projectInstance = None ... def __init__(self, *args, **kwargs): instance = kwargs.get('instance', {}) project = instance.project ... projectInstance = project ... def save(self, commit=True): ... if 'date_received' in self.changed_data: if not data['date_received'] == '': ... projectInstance.date_deposit_received = deposit.date_received ... else: ... ... ... return ... The exception that I'm getting in the console says: NameError: global name 'projectInstance' is not defined [25/Nov/2016 13:28:54] "POST /projects/6311/concept_save_ajax/ HTTP/1.1" 500 19430 Exception in thread Thread-42: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/Users/elgan/Documents/Dev/moonhub/moon/core/models.py", line 138, in run msg.send(self.fail_silently) File "/Users/elgan/.virtualenvs/moon/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/Users/elgan/.virtualenvs/moon/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/Users/elgan/.virtualenvs/moon/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 67, in open self.connection.login(self.username, self.password) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 615, in login raise SMTPAuthenticationError(code, resp) SMTPAuthenticationError: (535, '5.7.3 Authentication unsuccessful') What I don't understand is why the exception is telling me that … -
Django Model append phrase to app_label
I am doing some external integrations to save data to Django models. The integrations are taking some time. So I would like to create some temporary duplicate models. class MyModelAbstract(models.Model): my_field = models.CharField(max_length=50) ... class Meta: abstract = True class MyModel(MyModelAbstract): is_active = models.BooleanField(default=True) class MyModelTemp(MyModelAbstract): pass If my apps name is my_app than the table names are becoming my_app_mymodel and my_app_mymodeltemp. I would like to name it like my_app_tmp_mymodeltemp. I can accomplish this with following: class MyModelTemp(MyModelAbstract): class Meta: app_label = 'my_app_tmp' But I don't want to write app_label statically. If I change the name, I do not want to alter app_label by hand. I want to specify it like app_label = '%s_tmp' % app_label but I cannot access current app's label in the inner Meta class. Furthermore I can handle this with creating new meta class for this case. I am looking for a simpler approach. -
Modify data after Django form submission
I'm looking for let to users the possibility to modify forms which were created in order to correct mistakes during the filling process. There is some user steps (I'm blocked at the step 4) : 1) An empty form is presented on the HTML page 2) Users filled the form and click on the submit button which let to validate data and save objects in the MySQL Database. 3) I display kind of resume in order to verify if all data are corrects 4) I would like to put a button Modify just below my resume. Users could modify one or several fields and update the MySQL Database. The problem is as following : I have not idea about the way to do that (step 4). As I'm beginning with Django, is it possible to get some advices or part of script ? views.py : def IdentityFormulary(request) : form = IdentityForm(request.POST or None) if form.is_valid() : instance = form.save() return HttpResponseRedirect('formulaire_traite') context = { "form" : form, } return render(request, 'form_Identity.html', context) def CompletedFormulary(request) : identity = Identity.objects.all().order_by("-id")[0] context = { "identity" : identity, } return render(request, 'recapitulatif_identity.html',context) My HTML Template : <h2 align="center"> Votre formulaire a été validé </align> … -
Django Form that contains formset
I have forms, no orm, form is used only for data sanitising and validation: from django import forms from django.forms import formset_factory class ReviewTagForm(forms.Form): review_tags = forms.CharField() ReviewTagFormSet = formset_factory(ReviewTagForm) class ReviewForm(forms.Form): name = forms.CharField() review_tags = ReviewTagFormSet() # request.POST looks like this: # { # 'tags': ['dogs', 'cats', 'parrots'], # 'name': 'some fancy name', # } What I am aiming for is: form = ReviewForm(request.POST, request.FILES) form.is_valid() print(form.cleaned_data) > { > 'tags': ['dogs', 'cats', 'parrots'], > 'name': 'some fancy name', > } However it's not what I get, notably tags is missing. -
Sync database content with django
We have a local sqlite3 and an online mariaDB database and want to sync the content within django 1.10.3. The settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'online_database', 'USER': 'xxx', 'PASSWORD': 'xxxxx', 'HOST': 'xxx.xxx.xxx.xxx', }, 'local':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'local_database' } } With python manage.py migrate --database=local we were able to sync all the model structures but additionally we are interested in syncing the content of the tables. Is there anything implemented in django? -
Django crispy-forms: No i18n?
In a Django project, I translate strings using ugettext from the django.utils.translation module. As an example, I translate strings in my models.py. Translation works perfectly, but not with crispy-forms. Why is that and how can I fix this? Example models.py: from django.utils.translation import ugettext as _ class CustomerUser(models.Model): LANGUAGE_CHOICES = ( ('en', _('English')), ('de', _('German')), ) name = models.CharField(null=False, blank=False, max_length=50) user = models.ForeignKey(User, blank=True, null=True) email = models.EmailField(blank=True, null=True) language = models.CharField(choices=LANGUAGE_CHOICES, default='en', max_length=2) customer = models.ForeignKey(Customer) changed_password = models.BooleanField(default=False) def __unicode__(self): return self.name In the view, I do the following: from django.utils import translation translation.activate('de') but crispy forms aren't translated. The option from the language is still rendered as "German" instead of "Deutsch". -
How to get user permissions for non supervisor user by using request user attribute
I developed an django app which register user and give resources based on resource level permissionIn this I am using django basic level permissions on my model and templates, there for view permission I set permission tuple in my model like: class Model(AbstractUser): group = models.ForeignKey(AppGroup) class Meta: permissions = ( ('view_app', 'user can view app'), ) and I migrate my model after create my model like above. Now for permissions, I created a group from admin and including all app view/change/delete permissions, using that group I generated a drop down in form class. Now user(admin) can create other users based on selected permissions and after register successfully the new user able to login successfully and access all resources but when I am trying to access user permissions which is a many-to-many relationship using like class UserListView(ListView): def get_queryset(self): print(self.request.user.user_permissions.all()) return super(UserListView, self).get_queryset() When I list my view, it gives me a relation error (500 error): relation views_list_user_permission does not exist Now when I access the same view by superuser it gives me all permissions, but from a user which is neither superuser nor staff it spit out the above error. By reviewing djancgo.contrib.auth.models PermissionMixin class code it seems like … -
Handle streaming response on angularjs
I am using the Django StreamingHttpResponse Object to send a stream of responses to my angular client. I want to be able to use this streaming response to update my scope uopn recieving each stream. Is there a way to do this without using sockets? -
Bypass nginx cache if user is authenticated Django
I'm implementing nginx as a reverse proxy for a Django project. I'm now trying implement nginx's cache config below: proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:5m max_size=1g inactive=60m; proxy_temp_path /var/cache/nginx/tmp; server { ... location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; # cache proxy_cache my_cache; proxy_cache_min_uses 1; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_ignore_headers X-Accel-Expires Expires Cache-Control; proxy_cache_use_stale error timeout invalid_header http_500 http_502 http_503 http_504; proxy_cache_lock on; proxy_hide_header "Set-Cookie"; add_header X-Proxy-Cache $upstream_cache_status; } } All works great, however I'd like it so that authenticated users are able to bypass the cache, as otherwise when they update the site content, they won't see the changes, only the cached content until it expires. What would be the best way to approach this? Any help would be much appreciated. Thanks -
how to get multiple data when update data with django?
I want to update data using multiple checkbox this is my view.py def update_kel_stat(request, id): if request.method == "POST": cursor = connection.cursor() sql = "UPDATE keluargapeg_dipkeluargapeg SET KelStatApprov='3' WHERE (PegUser = %s )" % id cursor.execute(sql) and this is my template.html <form method="post" action="" name="kel" enctype="multipart/form-data"> {% for keluarga in kels %} <tr id="{{ keluarga.KelID }}"> <td> <a href="#">{{ keluarga.KelNamaLengkap }}</a> </td> <td>{{ keluarga.KelStatApprov }}</td> <td>{{ keluarga.KelKetRevisi }}</td> <td><input type="checkbox" name="kel[]" value="{{ keluarga.KelID }}"></td> </tr> {% endfor %} <tr> <td> <button type="button" name="btn_delete" id="btn_delete" class="btn btn-success" onClick="setDeleteAction();">Approve </button> </td> </tr> </form> how to get multiple value from checkbox in template.html to django view.py? -
python 3.5 /Django 1.10 Organizational Chart - OrgChart
I'm trying to build an dynamic organizational chart. My goal is something like this! But i need help to convert that in Python/Django. my models.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey class Qop(models.Model): class Meta: ordering = ['qop_ref'] verbose_name = 'Quadro Orgânico Pessoal' verbose_name_plural = 'Quadro Orgânico Pessoal' qop_ref = models.CharField(max_length=255, null=True, blank=True, verbose_name='Referência') qop_nome = models.CharField(max_length=255, null=True, blank=True, verbose_name='QOP Nome') qop_dt_arov = models.DateField(null=True, blank=True, verbose_name='Data de Aprovação') qop_atv = models.BooleanField(default=True, verbose_name='Ativo?') def __str__(self): return '{} {}'.format(self.qop_ref, self.qop_nome) class RefOrg(models.Model): class Meta: ordering = ['ref'] verbose_name = 'Refª - Subunidades/Orgão' verbose_name_plural = 'Refª - Subunidades/Orgãos' qop = models.ForeignKey(Qop, null=True, blank=True, related_name="qop2", verbose_name='QOP') ref_sup = ChainedForeignKey("self", chained_field="qop", chained_model_field="qop", show_all=False, auto_choose=True, sort=True, null=True, blank=True, related_name="ref1", verbose_name='Subunidade/Orgão Superior') ref = models.CharField(max_length=255, null=True, blank=True, verbose_name='Referência') su_org = models.CharField(max_length=255, null=True, blank=True, verbose_name='Subunidade /Orgão') def __str__(self): return '{} {}'.format(self.ref, self.su_org) Thank you in advance! -
How to fetch values from getlist in python django
The problem is with receiving the getlist method in django. I did like this. def fetchcheck(request): x = request.GET.getlist("chk") return render_to_response('music/fetchcheckvalues.html', RequestContext(request, {'x':x})) But I'm getting ukeys values as u'[]'. When I checked with just request.GET I got the values as u"{u'sita',u'ram'}>" So, How to get those values as a individuals in Django? -
On django admin why is django adding ?_changelist_filters to url?
Why django adds on url ?_changelist_filters=user%3D5275 when I click on add? My url on change_list was ?user=5275 initially. The issue is that the user should be selected in the select input and it isn't. If i change it in ?user=5275 is working. How can I make django to 'read'?_changelist_filters=user%3D5275 or to change it in ?user=5275 -
Django form- save() method only called on changes to certain fields [duplicate]
This question is an exact duplicate of: Python/ Django form tracking changes to some fields, but not to others I have a Django form on one of the pages of my site. The form is defined in forms.py with: class DepositInfoForm(ValidatedForm): amount_exc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency',}),label="Deposit exc VAT") amount_inc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency', 'readonly':'readonly',}),label="Inc VAT") date_received = mDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'}))) class Meta: model = Deposit fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received') def __init__(self, *args, **kwargs): print "__init__ method being called in DepositInfoForm" instance = kwargs.get('instance', {}) project = instance.project try: amount_exc_vat = int(round(instance.amount_exc_vat)) except TypeError: amount_exc_vat = None print "amount_exc_vat has been set: ", amount_exc_vat try: amount_inc_vat = int(round(project.deposit.amount_inc_vat)) except TypeError: amount_inc_vat = None print "amount_inc_vat has been set: ", amount_inc_vat try: date_received = instance.date_received except TypeError: date_received = None print "date_received has been set: ", date_received initial = kwargs.get('initial', {}) initial={ 'received': project.deposit_received, 'amount_exc_vat': amount_exc_vat, 'amount_inc_vat': amount_inc_vat, 'date_received': date_received, } kwargs['initial'] = initial super(DepositInfoForm, self).__init__(*args, **kwargs) self.fields['date_received'].widget.attrs.update({'data-original-value': self.initial['date_received'] or ''}) def save(self, commit=True): print "Save method being called in DepositInfoForm" deposit = self.instance data = self.cleaned_data print "save method being called in DepositInfoForm (projects/forms.py line 1142)" if 'date_received' in self.changed_data: if not data['date_received'] == '': deposit.project.deposit_received = … -
Django UNIQUE constraint failed with OneToOneField while migrate in Django User Model
In database I have already registered 4 persons but they were registered when model hasn't had relation attributes yet. When I added them I got this model: class Person(User): type = models.BooleanField() avatar = models.ImageField(blank=True) second_name = models.CharField(max_length=30, blank=True, default='') birthday = models.DateField(blank=True, default=None) country = models.CharField(max_length=30, blank=True, default='') city = models.CharField(max_length=30, blank=True, default='') school = models.CharField(max_length=60, blank=True, default='') university = models.CharField(max_length=60, blank=True, default='') work_place = models.CharField(max_length=60, blank=True, default='') profession = models.CharField(max_length=60, blank=True, default='') phone = models.CharField(max_length=30, blank=True, default='') about = models.TextField(blank=True, default='') latitude = models.FloatField(blank=True, default=-1) longitude = models.FloatField(blank=True, default=-1) friends = models.ForeignKey( 'self', related_name='+', ) black_list = models.ForeignKey( 'self', related_name='+', ) dialogues = models.ManyToManyField( 'dialogues.Dialogue', ) news = models.OneToOneField( 'news.NewsList', ) wall = models.OneToOneField( 'blogs.Blog', ) But now when this model migrates I have the error: django.db.utils.IntegrityError: UNIQUE constraint failed: persons_person.wall_id. -
Output colored logs from django with through supervisor and docker-compose
My objective is to get colorized logs of my Django webservice in docker-compose logs. I use docker-compose to manage a list of web services based on Django framework. Each container, run a my_init bash script, which in turn run a runit (this is historic in my case) script which runs a supervisord process: my_init---runsvdir-+-runsv---run---supervisord-+-gunicorn---gunicorn | |-nginx---8*[nginx] | |-python---9*[python] | |-python---python (Django) | `-redis-server---2*[{redis-server}] `-runsv The Django server is interfaced in WSGI with a Gunicorn, and served through a Nginx The supervisord conf is the following: [supervisord] http_port=/var/tmp/supervisor.sock ; (default is to run a UNIX domain socket server) stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 [program:gunicorn_core_service] #environment=myapp_VENV=/opt/myapp/venv/ environment=PYTHONPATH=/opt/myapp/myappServer/myappServer command = /opt/myapp/venv/bin/gunicorn wsgi -b 0.0.0.0:8000 --timeout 90 --access-logfile /dev/stdout --error-logfile /dev/stderr directory = /opt/myapp/myappServer user = root autostart=true autorestart=true redirect_stderr=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 [program:django-celery] command=/opt/myapp/venv/bin/python ./manage.py celery --app=myappServer.celeryapp:app worker -B --loglevel=INFO directory=/opt/myapp/myappServer numprocs=1 stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 redirect_stderr=true autostart=true autorestart=true startsecs=10 [program:nginx] command=nginx -g "daemon off;" #user = root autostart=true autorestart=true redirect_stderr=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 Since docker can only log once process, the logs of all the process of my container are forwarded to /dev/stdout and /dev/stderr And I use colorlog as color formatter to colorize Django logs: 'formatters': { 'color': { '()': … -
New Django(1.10) Project Loading Static Files (css) From an Older Django Project
Css File I Added @import url('https://fonts.googleapis.com/css?family=Ubuntu'); @import url('https://fonts.googleapis.com/css?family=Exo|Exo+2'); body { margin: 0; background: url("/static/img/img3.jpg"); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; min-height: 100%; overflow-x: hidden; } Css File That is Loading up on the test server body, html { font-family: 'Open Sans', sans-serif; text-rendering: optimizeLegibility !important; -webkit-font-smoothing: antialiased !important; color: rgba(255,255,255,0.5); width: 100% !important; height: 100% !important; } Settings.py INSTALLED_APPS = [ 'Home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' HTML <link rel="stylesheet" href="/static/css/style.css"> What am i Doing Wrong Please Help! The CSS page that is loading is from an older project which i have already deleted. I even tried to reset the migrations using "python manage.py makemigrations" is says "No Changes Detected" Thank You -
I want to display all the links related to the page 'www.pythonforbeginners.com' line by line. How can I solve it?
from django.shortcuts import render from bs4 import BeautifulSoup import urllib2 def home(request): url = urllib2.urlopen("http://www.pythonforbeginners.com") readurl = url.read() soup = BeautifulSoup(readurl) links = soup.find_all('a') for lin in links: result = lin.get('href') return render(request, 'search/homepage.html', {'result': result, 'url':url}) {{ result }} -
How to play sound in ajax response
i want to make sound allert in ajax response I.m using django framework, and I call ajax function every 20 seconds to update table values. AJAX request looks like: <div> {% if new_orders.count > 0 %} {% for new_order in new_orders %} <li> {{new_order.order_title }} <a href="confirm/{{new_order.id}}">conform</a> </li> {% else %} {% endif %} </div> So simplyfied question, is how to play sound in {% if new_orders.count > 0 %} on ajax response? -
Cant install mod_wsgi in Django on Mac
Ive been having trouble installing mod_wsgi on Django. This is the traceback for the terminal. I'm using macOS Mac-mini-3:~ Sqooge_Ahmed$ pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.5.7.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/14/x0m8m6p16bs9mfrmrs54zrjc0000gn/T/pip-build-0NyGFW/mod-wsgi/setup.py", line 247, in <module> APR_INCLUDES = get_apr_includes().split() File "/private/var/folders/14/x0m8m6p16bs9mfrmrs54zrjc0000gn/T/pip-build-0NyGFW/mod-wsgi/setup.py", line 219, in get_apr_includes stdout=subprocess.PIPE, stderr=subprocess.PIPE) File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1343, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/14/x0m8m6p16bs9mfrmrs54zrjc0000gn/T/pip-build-0NyGFW/mod-wsgi/ Can anyone help plz. thank you. -
django table column reads None incorrectly
Witch django I am creating the mysql table MariaDB [ipp_database]> SELECT * FROM polls_question; +----+----------------+----------------------------+ | id | question_text | pub_date | +----+----------------+----------------------------+ | 1 | What's up? | 2016-10-06 11:04:36.703335 | | 2 | Klappt das so? | 2016-11-24 09:39:11.953693 | | 3 | Klappt das so? | 2016-11-24 09:40:08.260329 | | 4 | Klappt das so? | 2016-11-24 10:32:54.000000 | | 5 | Klappt das so? | 2016-11-24 10:32:57.000000 | +----+----------------+----------------------------+ 5 rows in set (0.00 sec) with the model from __future__ import unicode_literals from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text and the Command from django.core.management.base import BaseCommand from polls.models import Question from django.utils import timezone class Command(BaseCommand): def handle(self, *args, **kwargs): q = Question(question_text="Klappt das so?", pub_date=timezone.now()) q.save() for question in Question.objects.order_by('id'): print u"%s %s %s" % (question.id, question.question_text, question.pub_date) In the mysql terminal it is showing correctly but when reading with the command posted it gives 1 What's up? None 2 Klappt das so? None 3 Klappt das so? None 4 Klappt das so? None … -
Auth0 JWT plugin and ionic2 - No Authorization header send
I have problem with integrating JWT token plugin from Auth0 with least Ionic2. I have absolutly no error but request is send without authorization header. My code: app.module import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { MyApp } from './app.component'; import { AboutPage } from '../pages/about/about'; import { ContactPage } from '../pages/contact/contact'; import { HomePage } from '../pages/home/home'; import { TabsPage } from '../pages/tabs/tabs'; import { LoginPage } from '../pages/login/login'; import { AuthHttp, AuthConfig } from 'angular2-jwt'; import { Storage } from '@ionic/storage'; import { Http } from '@angular/http'; import { AuthService } from '../services/auth.service'; import { NoteService } from '../services/note.service'; let storage: Storage = new Storage(); export function getAuthHttp(http) { return new AuthHttp(new AuthConfig({ headerPrefix: 'JWT', noJwtError: true, globalHeaders: [{'Accept': 'application/json'}], tokenGetter: (() => storage.get('id_token')), }), http); } @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage, LoginPage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage, LoginPage ], providers: [ AuthService, AuthHttp, { provide: AuthHttp, useFactory: getAuthHttp, deps: [Http] }, Storage, NoteService, ] }) export class AppModule {} my service: import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import { AuthHttp } … -
Mysql GeoDjango Distance search
Is there any pure Django/faster way to get the distances less than x km. I have the model class Location(models.Model): title = models.CharField(max_length=10) point = models.PointField(srid=32140, null=True, blank=True) So I want to search the locations less than x km in mysql.? Because distance less than is only supported in postgresql. I want to do in mysql database. Thanks. -
"Cannot assign / must be an instance" error when creating a model instance from a CSV (ForeignKey related)
(I have read a few related questions, but none seems to have the answer for my particular problem, or perhaps I have misunderstood them.) In my app I have a model Kurs, and each Kurs is assigned to a user in this way: class Kurs(models.Model): prowadzacy = models.ForeignKey(User) I want to populate my database of Kurs's from a CSV. The 0th element of each row is a username. So in my reader routine I wrote what follows (skipping the, I hope, irrelevant details): n = Kurs() n.prowadzacy = User.objects.get(username=row[0]) Now, in the shell, when I do this, what I'm getting is, I thought, a User instance: >>> User.objects.get(username='leszekwronski') <User: leszekwronski> But when I run my reader routine it tells me it does not actually have a User instance to assign to the 'prowadzacy' field: ValueError: Cannot assign "'leszekwronski'": "Kurs.prowadzacy" must be a "User" instance. What am I doing wrong? (I considered that maybe I'm getting the id of the User, so I also halfheartedly tried n.prowadzacy = User.objects.get(id=User.objects.get(username=row[0]))` but arrived at the same error.)