Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - get serialized fields from related model
I can't figure out how to serialize a query that includes fields from a reverse related model. My models look like this. Every vote is linked to a single album: # models.py class Album(models.Model): name = models.CharField(max_length=50) class Vote(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) user_vote = models.BooleanField(default=0) Now what I'd like to do is perform a query that returns all Album objects, as well as a sum of the votes attributed to that album. That's easy enough, but when I serialize the query, the "total_votes" field is lost: # views.py # this works fine query = Album.objects.annotate(total_votes = Sum(vote__user_vote)) # after serialization, I lose the field "total_votes" serialized = serializers.serialize('json', list(query)) return serialized Unfortunately, the field "total_votes" doesn't appear in the serialized result since, according to Django documentation, "only the fields that are locally defined on the model will be serialized." So my question is, how do I get the following serialized result (assuming there are 100 votes for Abbey Road and 150 for Astral Weeks)? Any help would be greatly appreciated. [ { "pk": 1, "model": "app.album", "fields": { "name": "Abbey Road", "total_votes": 100 }, { "pk": 2, "model": "app.album", "fields": { "name": "Astral Weeks", "total_votes": 150 }, ... ] -
Server Error (500) when trying to log in in Django admin page
I am having a little project and am trying to set up a website using Django, Apache 2 and mod_wsgi. Everything runs fine in the Django development server, and I can also open the front page of my site using apache. However, when I try to log in into the admin page, or use my own custom log in page, I get a Server error (500). Can anyone tell me what I am doing wrong? settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = ... DEBUG = True ALLOWED_HOSTS = ["localhost", "192.168.0.121", "127.0.0.1"] LOGIN_REDIRECT_URL='/account' LOGOUT_REDIRECT_URL='/login' INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'kraken.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'kraken.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") … -
Django allauth: Visit login page but already logged in
Can you set django-allauth to have a redirect link if you visit the login page and you're already logged in? -
Certain command used in Ubuntu, but for Django
I'm used to with Ubuntu, but it is a little bit different for Django. With Ubuntu, it is easy to find documentation about a command (i.e., man ourcommand), but what about Django. I mean when I go on the terminal when could install django with the simple command pip install django. After that, a guy has used the pip3 freeze command, and I was wondering if it is possible to do the same thing as with Ubuntu. Question : Is there exists a command like man command but with django to find more information about a command (e.g. 'man' freeze)? Thanks in advance! -
Need help creating a ChoiceField form with CheckBoxSelectMultiple widget by passing an argument from views
I am trying to pass an argument from views.py to forms.py to create a "ChoiceField()" with "CheckboxSelectMultiple()" widget but the render fails due to error Exception Type: AttributeError Exception Value: 'list' object has no attribute 'get'. Could you please take a look below and throw some light as to what I am doing wrong :( Thanks for your help in advance. forms.py class TestSubmitForm(forms.Form): def __init__(self,*args,**kwargs): self.testList = args[0] super(TestSubmitForm,self).__init__(*args,**kwargs) pdb.set_trace() self.fields['tests'].widget = forms.CheckboxSelectMultiple() self.fields['tests'].choices = self.testList tests = forms.ChoiceField() views.py def index(request): tc_obj_form = [("","1"),("","2"),("",3")] tests = TestSubmitForm(tc_obj_form) return render(request, 'index.html',{'tests':tests}) index.html </form> {% if tests %} <div align="bottom" style="height:100;width:1024;border:solid"> <form action="." method="POST"> <div style="overflow-y: scroll;"> <table > {% csrf_token %} {{tests}} </table> </div> <input type="submit" value="Submit"/> </form> Traceback: File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/local/User/demo/web/apps/Lcloud/views.py" in index 94. return render(request, 'Lcloud/index.html',{'tc_filter_form':tc_filter_form,'tests':tests}) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/shortcuts.py" in render 48. return HttpResponse(loader.render_to_string(*args, **kwargs), File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 178. return t.render(context_instance) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/base.py" in render 148. return self._render(context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/debug.py" in render_node 80. return node.render(context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/loader_tags.py" in render 126. return compiled_parent._render(context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/local/User/demo/web/venv/lib/python2.7/site-packages/django/template/base.py" in … -
Best way to put url in django and jquery ajax
I'm new in django ajax. I wrote a script which is functional. But want to know is there any better option than this. $.ajax({ url: "{% url 'all_student' status='statuslink' %}".replace('statuslink',status), success: function(data){ var blog = $.parseJSON( data ); $.each( blog, function( i, val ) { var html_file = '<li class="shown">\ <a href="details/'+ val['pk'] +'">\ <img src="/media/'+ val['fields']['image_1'] +'">\ <div class="overlay">\ <p>'+val['fields']['name'] +'</p>\ </div>\ </a>\ </li>'; $('.result ul').append(html_file); }); } }); -
Greenplum Django migrate distribution key error
I am currently working on a Greenplum project. Part of this project is creating a simple webapp for the visualization and statistics of data. When I tried integrating Greenplum with Django it failed, giving me the following error: python manage.py migrate : UNIQUE index must contain all columns in the distribution key of relation django_content_type. It appears that Django cannot create some of its tables, specifically django_content_type. When the user doesn't specify a distribution key for Greenplum, the primary key is chosen and in the case of the django_content table, column id was chosen by default as the distribution key. Later on, Django tried to define django_content_type_app_labelas a UNIQUE value. The distribution key then was automatically redefined to match the unique field. However, the primary key (id) is not a subset of the distribution key, and this is one of the requirements of Greenplum. Is there a workaround to this migration issue to integrate Django with Greenplum? I have searched but not found anything helpful. Unfortunately, use of Greenplum is mandatory, so I cannot use another database. Alternatively, what framework could be used instead of Django? I know R applications are supported but this is also unfortunately not an option … -
Django Login in Views
I'm trying to login user from views getting an error 'User' object has no attribute 'backend' from django.contrib.auth import login def confirmation(request): ... login(request, user) -
New Recipe Database design. Categorize or filter?
Requirement: There are thousands of ingredients in given commercial kitchen. To simplify user interface, when entering a new recipe, show only ingredients relevant to the Food Category selected by user. For example, create a new cookie recipe -> display MultiSelectBox with only ingredients used in Cookies Simple Solution (?): A RECIPE belongs to one FOOD_CATEGORY. For example: Peanut Butter Cookie ---> Cookies INGREDIENT <- ManyToMany -> FOOD_CATEGORY Will this suffice to meet the above requirement, and are there any "gothas"? Another alternative is to use an Ajax style dynamic search box to simply filter on all ingredients as user begins to type. More broadly, is there a methodology that drives Database design from the UI to prevent any potential surprises. For example, after my initial design, I realized a MultiSelectBox with too many ingredients simply wouldn't work. -
In Django, how to cache a POST request to a view?
I'd like to cache a POST request with cache_page on a view in view.py: from django.views.decorators.cache import cache_page @cache_page(60 * 15) def get_data(request): ... return JsonResponse({...}) But this doesn't seem to be working. Am I missing something? Is there a way I can explicitly tell Django to cache POST requests for this view? -
Python AttributeError: 'Class' object has no attribute 'name' - SetUpClass
I'm writing tests for a model in a django app, but cannot get them to run. I've tried all I can think of to solve and searched but cannot find the solution. The error I receive when I run the test is AttributeError: 'UserModelTest' object has no attribute 'firstUser', which would suggest I haven't defined firstUser correctly. Please can you point out where I have gone wrong? Here are the relevant bits of code. tests.py file: from django.test import TestCase from .models import ContactForm from datetime import datetime, timedelta class UserModelTest(TestCase): @classmethod def SetUpClass(cls): cls.firstUser = ContactForm( email="first@user.com", name="first", timestamp=datetime.today() + timedelta(days=2) ) cls.firstUser.save() def test_contactform_str_returns_email(self): self.assertEqual("first@user.com", str(self.firstUser)) models.py: from django.db import models import datetime class ContactForm(models.Model): name = models.CharField(max_length=150) email = models.EmailField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ['-timestamp'] I think that's all the relevant information, but tell me if any more would help. I'm using Python version 3.5 and Django version 1.10. -
Extending login function from django.contrib.auth.views (Django project)
I'm using the versatile django-brake for rate limiting in my Django app. I now need to configure it to limit brute force login attempts in my app too. The way to do that is to decorate the login view with the decorator ratelimit(field='username') and adding was_limited = getattr(request, 'limited', False) inside the view. was_limited is True if the same username (OR IP) is used >5 times/min. One can then redirect offending users, etc. Now I'm using the login function in django.contrib.auth.views. What's the best way for me to decorate and extend this function to include the above functionality? I was thinking I'd decorate the login function in my urls.py. But I can't include was_limited = getattr(request, 'limited', False) inside the function that way. Do I need to override the whole thing? Please advise. Being a beginner, I'm trying to come up with the best way to deal with a situation like this. An illustrative example would be nice. -
NetworkX graph object running in Django
I would like to have a Networkx object running in my Django server so it can be instantaneously accessed by any view function. What is the best way to do that in terms of performance (if possible)? The idea is to have an object always there to be accessible in all moments without having to create a new one every time a request is made. Thanks! -
Django View always enters GET and never in POST method
I have the following view in my Django project class EditProfileView(generic.View): def get(self, request, *args, **kwargs): template = 'account/edit_profile.html' form = EditProfileForm(instance=request.user) countries = Country.objects.all() return render(request, template, {'form': form, 'countries': countries}) def post(self, request): user = get_object_or_404(User, email=request.user) form = EditProfileForm(request.POST) if form.is_valid(): user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.location = form.cleaned_data['location'] user.phone = form.cleaned_data['phone'] user.save() add_success_message(self.request, "Your profile was updated") return HttpResponseRedirect('/accounts/profile') referring to this form on the template <form method="post" action="/accounts/profile/update/"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success waves-effect waves-light" type="submit" value="{% trans "Save Changes" %}"/> </form> However, all that happens is, wether loading the page or submitting the form it ALWAYS enters the GET method, always. Any clue why this is happening? -
Django Q lookup works but displays << MISSING VARIABLE "request.GET.q" >> in my lookup field
I use Q lookups in all my projects but this is the first I have run into this. First off, the lookup works as expected, but the lookup field still displays << MISSING VARIABLE "request.GET.q" >> when refreshing the page. If the lookup didn't work, I could probably find the issue but I'm a bit stumped in this one. Below is by view and the template form. Thank you. View def product_list(request): queryset_list = Product.objects.prefetch_related('images').select_subclasses() query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 10) page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) form = forms.ProductClassForm(request.POST or None) if form.is_valid(): return redirect('dashboard:product-add') ctx = { 'form': form, "object_list": queryset, "title": "Products", "page_request_var": page_request_var, } return TemplateResponse(request, 'dashboard/product/list.html', ctx) Lookup Form <form method='GET' action=''> <label for="full-text">Search Product List</label> <input type="text" placeholder="Enter Keywords and Press Enter" class="search-input" name="q" value='{{ request.GET.q }}'> </form> -
Trouble setting-up directories to compile from in Django-Assets / Webassets
This is my current assets.py file: from django_assets import Bundle, register sass = Bundle( 'build/main.sass', filters='sass', output='css/main.css' ) register('sass', sass) Now I run into an issue with it saying Another bundle is already registered as "sass", but not seeing how to unregister it. At any rate, I change register('sass', sass) to register('sass_all', sass) to get past the error. When I go to compile it is looking in my scripts directory where I keep manage.py. In settings.py I add: ASSETS_ROOT = [ 'static', ] Which just has look in scripts/static which doesn't exist. Tried: # This is already in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Added new line ASSETS_ROOT = [ STATICFILES_DIRS, ] It generates a couple errors: KeyError: 'directory', OSError: The environment has no "directory" configured, and AttributeError: 'list' object has no attribute 'startswith'. Really it is just one error that directory isn't defined, I think. Read through environment documentation which is vague given my skill level. In assets.py adding Environment to import just says Could not import in Environment. Adding Environment.directory('static') results in Environment is not defined. Just directory('static') also results in directory is not defined. env = Environment() same thing. Tried adding directory='/static' to sass = … -
Server error 500 on sending email on Heroku
I have a django project. The user fills the form and then I receive a notification about new order. Localy, on my computer everything is ok. I deploy my application on Heroku and on the site I cannot send emails. I receive error 500. This is my code: settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL='sitename' views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.template.loader import render_to_string from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .forms import OrderForm def contact(request): company='no company' if request.method == 'POST' : form=OrderForm(request.POST) if form.is_valid(): company=form.cleaned_data['company'] try: msg_plain = render_to_string('../templates/publicity_agency/email.txt', {'company':company}) msg_html = render_to_string('../templates/publicity_agency/email.html', {'company':company}) msg_plain_client = render_to_string('../templates/publicity_agency/email_client.txt') msg_html_client = render_to_string('../templates/publicity_agency/email_client.html') send_mail('New order',msg_plain,'Notification <myemail@gmail.com>', ['myemail@gmail.com'], html_message=msg_html) send_mail('Order',msg_plain_client,'Order <myemail@gmail.com>', [email], html_message=msg_html_client) except BadHeaderError: return HttpResponse('Invalid header found') return redirect('contact') else: form=OrderForm() return render(request, 'publicity_agency/contacts.html', {'company':company}) Please, help me to resolve this issue -
Django group by consecutive days (Friday, Saturday, Sunday)
I have an event that occurs everyday. Here is the model class Event(models.Model): date = models.DateField() plays = models.IntegerField() viewers = models.IntegerField() time = models.FloatField() I am trying to aggregate the event by consecutive days (Friday, Saturday, Sunday). Note: Friday and Saturday are from the same week and Sunday from the next. Using raw queries (postgres) I can use the following query to aggregate SELECT DATE_TRUNC('week', "date")::date AS date, SUM(plays) AS total_plays, SUM(viewers) AS total_views, SUM(time) AS total_time FROM app_event WHERE extract(isodow FROM date) IN (5,6,7) GROUP BY date_trunc('week',"date") However in django I can't find a way to replicate the query queryset = Event.objects.filter(date__week_day__in=[1, 6, 7]).annotate('week'=TruncWeek('date')).values('week').annotate(total_views=Sum('views'), total_plays=Sum('plays'), total_time=Sum('total_time')).values('week', 'total_views', 'total_time', 'total_plays') However this query picks Sunday, Friday and Saturday in the same week -
Can I deploy my django app to the internet from home?
For some time ago I created a web application created with java servlets. And through my domain provider I could tell the domain to be hosted from my IP. And with an apache server I were able to host my own webpage and make it public. I'm curious if and how I'd do this with a django application? I tried searching around, but unfortunately all the tutorials or examples included a hosting service. I'm a rookie at servers, so I'm not sure wether apache will run django apps or if there's any other form of deployment acts that django requires. Are there any documentation or readings out there I could take use of? -
Django external api calls
I have a trouble calling external api. This is my view: class TestView(APIView): def call_api(self, request, *args, **kwargs): headers = {} url = 'http://jsonplaceholder.typicode.com/users/' method = request.method.lower() method_map = { 'get': requests.get, 'post': requests.post, 'put': requests.put, 'patch': requests.patch, 'delete': requests.delete } return Response(method_map[method](url, headers=headers, data=json.dumps(request.data)).json()) def get(self, request, *args, **kwargs): return self.call_api(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.call_api(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.call_api(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.call_api(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.call_api(request, *args, **kwargs) This is my urls.py: url(r'^test/(?P<pk>[0-9]+)/$', TestView.as_view()), How can i update my urls and call_api() to get one of users: test/1/, test/2. Now i have all users in that urls.py. Also i need this for all REST requests. Thanks. -
Django 1.10 error, 'NoneType' object is not callable
I'm trying to build a user signup page for a Django project. I have an app called custom_user in which the models.py file contains the following (apart from imports): class CustomUserManager(BaseUserManager): def create_user(self, identifier, password, email, full_name, date_of_birth): user = self.model( identifier=identifier, email=self.normalize_email(email), full_name=full_name, date_of_birth=date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, identifier, password, email, full_name, date_of_birth): # Almost same as previous method. class CustomUser(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() USERNAME_FIELD = 'identifier' identifier = models.CharField(max_length=40, unique=True) email = models.EmailField(max_length=200, unique=True) full_name = models.CharField(max_length=200) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) REQUIRED_FIELDS = ['full_name', 'email', 'date_of_birth'] def get_full_name(self): return self.full_name def get_short_name(self): return self.identifier In another app called sign_up, the view for signing up looks as: def index(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): # Create the new user. manager = CustomUserManager() user = manager.create_user( form.cleaned_data['identifier'], form.cleaned_data['password'], form.cleaned_data['email'], form.cleaned_data['full_name'], form.cleaned_data['date_of_birth'], ) return HttpResponseRedirect(reverse('sign_up:user_created')) else: form = CreateUserForm() return render(request, 'sign_up/index.html', {'form': form}) The views.py file imports the CreateUserForm class (placed in sign_up directory's forms.py): from django.forms import ModelForm from custom_user.models import CustomUser class CreateUserForm(ModelForm): class Meta: model = CustomUser fields = ['identifier', 'password', 'email', 'full_name', 'date_of_birth'] ... And finally the template used by the view contains: … -
Show columns of referenced table instead of the object in django admin
How can I show the columns id, title and the year of the book instead of "Books object"? This screenshot shows the current state: My model.py looks like this: from __future__ import unicode_literals from django.db import models class Authors(models.Model): name = models.CharField(max_length=45, blank=True, null=True) birthday = models.DateField(blank=True, null=True) class Meta: managed = True db_table = 'authors' class AuthorsBooks(models.Model): author_id = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author_id', primary_key=True) book_id = models.OneToOneField('Books', models.DO_NOTHING, db_column='book_id', primary_key=True) class Meta: managed = True db_table = 'authors_books' unique_together = (('author_id', 'book_id'),) class Awards(models.Model): author = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author', primary_key=True) award_name = models.CharField(max_length=45) year = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'awards' unique_together = (('author', 'award_name'),) class Books(models.Model): titel = models.CharField(max_length=45, blank=True, null=True) year = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'books' In the class AuthorsBooks I have changed the two foreign keys to OneToOneFields. My admin.py looks like this: from django.contrib import admin from myapp.models import Authors ... class AwardsInline(admin.TabularInline): model = Awards class AuthorsBooksInline(admin.TabularInline): model = AuthorsBooks class AuthorsAdmin(admin.ModelAdmin): list_display = ("name", "birthday" ) inlines = (AwardsInline, AuthorsBooksInline) admin.site.register(Authors, AuthorsAdmin) -
Django: Passing DetailView pk to FormView
I'm trying to create a modal form in a generic DetailView where user can make me aware of errors related to that specific object. When the form is submitted the user is supposed to return to the same page (the same DetailView) but I have problems figuring out how to pass the primary key to the success_url of the FormView. forms.py: class ErrorView(AjaxTemplateMixin, FormView): form_class = ErrorForm template_name = 'app/error.html' def get_success_url(self, **kwargs): return reverse_lazy('feriehus_detail', kwargs={'pk': self.object.pk}) def form_valid(self, form): form_content = form.cleaned_data['content'] template = get_template('error_template.txt') context = Context({ 'form_content': form_content }) content = template.render(context) email = EmailMessage( 'Fejl', content, 'Your website ' + '', ['youremail@gmail.com'] ) email.send() return super(ErrorView, self).form_valid(form) urls.py: url(r'^error/$', views.ErrorView.as_view(), name='error'), url(r'^feriehus/(?P<pk>[0-9]+)/$', views.FeriehusDetail.as_view(), name='feriehus_detail'), This part is not working: kwargs={'pk': self.object.pk}) -
Django can't find existing document using ObjectId with mongoengine
I'm trying to update a document from my mLab using mongoengine. I have an existing ObjectId from a document but when I try to get it using the obtained id my search list is empty. Here's my update code: def update(request): if request.method == "POST": _id = request.POST.get('_id',ObjectId()) geometry = request.POST.get('geometry', '') properties = request.POST.get('properties','') try: route_test = Route.objects(id=ObjectId(_id)) print(route_test) Route.objects(id=ObjectId(_id)).update(set__geometry=geometry, set__properties=properties) return HttpResponse("Success!") except: return HttpResponse("Error!") my route_test would contain nothing : [ ]. Is something wrong with my query? I even tried the following variation: Route.objects(id=_id), Route.objects(_id=ObjectId(_id)) -
Steps in migrating a Django project to an Anaconda/conda environment
Background: I've been developing a Django project for myself for a while, I started from no Django knowledge and limited python knowledge. The project is in a virtual-env. Recently, I decided to add some analytics to my Django app but kept getting errors installing scipy and numpy. In looking for a solution, I found the Anaconda package/collection and realised this did everything I needed for my project and would be ideal for future projects I'm considering. I'm not quite sure what steps to take in migrating my project. TL;DR: Started as django novice in virtualenv, found Anaconda, want to migrate project Queries: DB - I have heard that South is a useful tool for migrating the db, although I'm sure I also read that it has been deprecated. Apps - I think that I can basically copy and paste the views, urls, templates, forms, etc. I'd just like to check before doing something catastrophic... I also want to start using some form of VCS, probably git due to it's popularity. Any advice on starting with git would be helpful. Basically, my questions are about any common pitfalls in migrating django projects and how to avoid them. I'm asking this in …