Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LiveServerTestCase hangs when I run my tests
I am trying to set up a LiveServerTestCase with Django 1.10.4. Whenever I run my tests the the browser opens up hangs and can't reach localhost. My frontend is a separate angular/react app. So, I build my static assets using grunt build and then run collectstatic. Below is the code for my tests. from django.test.testcases import LiveServerTestCase from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class ChromeTestCase(LiveServerTestCase): @classmethod def setUpClass(cls): super(ChromeTestCase, cls).setUpClass() cls.driver = webdriver.Chrome('/path/to/chromedriver') cls.driver.implicitly_wait(10) cls.wait = WebDriverWait(cls.driver, 10) @classmethod def tearDownClass(cls): cls.driver.quit() super(ChromeTestCase, cls).tearDownClass() def test_user_sign_up_from_form(self): self.driver.get('%s%s' % (self.live_server_url, '/')) self.wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="email"]'))) email_input = self.driver.find_element_by_xpath( '//input[@id="email"]') email_input.send_keys("test@gmail.com") password_input = self.driver.find_element_by_xpath( '//input[@id="password"]') password_input.send_keys("secret") signup_button = self.driver.find_elements_by_xpath( '//*[@id="signup_button"]') signup_button.click() url = self.live_server_url + '/home' self.assertEquals(self.driver.current_url, url) Does anyone know why my tests can't reach the test server? -
Django Unit Tests on Bamboo
I am using Django 1.9.6. I have, for example, the following model in my models.py file: class Question(BaseModel): user = models.ForeignKey(User, null=True, blank=True) question_type = models.ForeignKey(QuestionType, null=True, blank=True) question_template = models.ForeignKey(QuestionTemplate, null=True, blank=True) question_text = models.CharField(max_length=500, unique=True) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __unicode__(self): return ( u"Question id: {}".format(self.id) ) and in tests.py I am running the following test on it: class TestQuestionModel(TestCase): def setUp(self): Question.objects.create(question_text="What is the airspeed velocity of an unladen swallow?") def test_simple_questions(self): simpleQuestion = Question.objects.get(question_text="What is the airspeed velocity of an unladen swallow?") self.assertEqual(simpleQuestion.question_text, "What is the airspeed velocity of an unladen swallow?") And I'm using a postgres database. This all works hunky-dory locally. I understand that I need to convert the output to JUnit XML to run the tests in Bamboo, but I am getting a little stuck. This answer got me 90% of the way there, but I am struggling to figure out the postgres part. The script I am running before the JUnit Parser is as follows: #installing pip locally wget https://bootstrap.pypa.io/get-pip.py python get-pip.py --root=${bamboo.build.working.directory}/tmp --ignore-installed export PATH=${bamboo.build.working.directory}/tmp/usr/local/bin:$PATH export PYTHONPATH=${bamboo.build.working.directory}/tmp/usr/local/lib/python2.7/dist-packages:$PYTHONPATH echo Pip is located `which pip` # setting up virtualenv pip install --root=${bamboo.build.working.directory}/tmp --ignore-installed virtualenv virtualenv . ./bin/activate # get … -
Getting tweets in real time in tweepy and displaying on template
I have a program in which i need to get 15 latest tweets after every time (for example after every 5 seconds) and then displaying the latest tweets on the template. For now i'm getting just the latest 20 tweets, what i need are live tweets relative to a hashtag and then display the live stream as it comes on the django template. How can i achieve that? For now i have: import tweepy from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener auth = tweepy.OAuthHandler('') auth.set_access_token('') api = tweepy.API(auth) hashtag = "#trump" search_number = 20 search_result = api.search(hashtag,rpp=search_number) for i in search_result: print i.text.encode('utf-8'),"\n" -
python bokeh unit tests
I was wondering if there were any strategies or implementations to unit testing of a bokeh plot rendered within a Django template other than looking at the response status code of the Django view? Here is my code snippet below, #views.py def bokeh_view(request): ... script,div = components(mygraph) return render(request, 'graph.html',{'script': script, 'div': div}) #graph.html ... {{ div | safe }} {{ script | safe }} ... #test.py def test_dashboard(self): responce = self.client.post('/bokeh_view/', follow=True) self.assertEqual(response.status_code, 200) I also have user forms which may affect the database tables from which will then be graphed. I do not have access to selenium currently so all tests are running via Django's test runner. -
Django URL Multiple-Routes Pattern Not Injective
I'm trying to include optional URL patterns in my Django project by adapting the multiple-routes pattern explained in this SO post. In my urls.py file I have the following patterns. urlpatterns = [ url(r'^(?P<slug>[-\w]+)\/?$', View.as_view()), url(r'^(?P<section>[-\w]+)\/(?P<slug>[-\w]+)\/?$', View.as_view()), url(r'^(?P<section>[-\w]+)\/(?P<tag>[-\w]+)\/(?P<slug>[-\w]+)\/?$',View.as_view()), ] The parameters section, tag, and slug correspond to model fields. So a HTTP request to /foo/bar/baz returns a model instance with a "foo" section, "bar" tag, and "baz" slug. Not all model instances have a section or tag, those parameters are optional. If you think about the URL dispatcher as a function with a domain of URLs and a codomain of model instances, the pattern I'm using isn't an injective function. /baz, /foo/baz, and /foo/bar/baz return the same model instance, but only the last URL should return the model instance. In short, how do I configure my urlpatterns to return my foo-bar-baz model if, and only if, the requested URL is /foo/bar/baz? -
Button to create new page
I'm new to Mezzanine and django, in this moment I'm trying to make a button in a page template, the idea is to allow the registered user to do two things: create a new daughter page of the current page add an access link to a list of links of the current page I would like to make a popup appear that asks for the name and content of the new page, I do not know if what I need is very complex to do with mezzanine, I study the djangogirls tutorial (tutorial.djangogirls.org) and I reviewed the examples of the mezzanine documentation (mezzanine.jupo.org/docs/content-architecture.html), but I do not see how to do what I need, this is the link for my mezzanine project: github.com/Dacastror/inicio_mezzanine in advance I appreciate the help. -
Django image-cropping: How use with StackedInline
I'm trying to use admin.StackedInline in a admin django view but is not working, more specifically, the thumbnail doesnt show on stacked, when using the django-image-cropping app Image with the admin.StackedInline not showing the Thumbnail On the other hand, if I use a normal admin view just for show the Thumbnail and use the crop function of the django app, magically works... Exclusively admin view for the Image ForeignKey, this time showing the Thumbnail Someone can help me? I Think the problem is in the way I implemented the stackedinline in the admin, because I didn't understand in depth how to use, but it can be in the app: django-image-cropping For more detail in the code, I'm just using the example in the github repository of the django app: github.com/jonasundderwolf/django-image-cropping/tree/master/example here are the snippets model.py from django.db import models from image_cropping.fields import ImageCropField, ImageRatioField class Image(models.Model): image_field = ImageCropField(upload_to='image/') cropping = ImageRatioField('image_field', '120x100', allow_fullsize=True) cropping_free = ImageRatioField('image_field', '300x230', free_crop=True, size_warning=True) class Meta: app_label = 'example' def get_cropping_as_list(self): if self.cropping: return list(map(int, self.cropping.split(','))) class ImageFK(models.Model): image = models.ForeignKey(Image) cropping = ImageRatioField('image__image_field', '600x300') class Meta: app_label = 'example' admin.py from django.contrib import admin from image_cropping.admin import ImageCroppingMixin from .models import Image, ImageFK … -
Configure Django Database Routers
I am trying to connect a new Django site to legacy DBs. From everything I can gather I need to create a database router. The docs refer to creating an app_label in the meta section of the model. This is what the router would match to. I have also seen where people say this is not longer supported. I am racking my brain here please help!! Here is the code: class CucRouter(object): def db_for_read(self, model): if model._meta.app_label == 'CUCMCDR': return 'CUCMCDR' return 'default' That is the router function and is essentially the example from the docs. In the model I added this line: app_label = 'CUCMCDR' This breaks the server with an error return that there is "no app named CUCMCDR" (which there shouldnt be. CUCMCDR is the name of the db) -
HighChart pie does not display any data
Pie Chart looks like this: Data is there in JSON: When i tried it with type of "bar" or "column" chart it works fine. Still new to this and really appreciate your help, folks! Django version: 1.10 Python version: 3.6 chartViewHigh.html {% block main %} <h1 align="center">Analysis</h1> {% block content %} <div id="container" style="width:50%; height:400px;"></div> {% endblock %} {% block extrajs %} <script> var endpoint = '/api/chart/data/'; var labels = []; var defaultData = []; var labels2 = []; var defaultData2 = []; $.ajax({ method: "GET", url: endpoint, /** * @param data * @param data.labels * @param data.default * @param data.default2 */ success: function (data) { labels = data.labels; defaultData = data.default; labels2 = data.labels2; defaultData2 = data.default2; setChart() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); function setChart() { $(document).ready(function() { var chart = { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }; var title = { text: 'Total' }; var tooltip = { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }; var plotOptions = { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}%</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }; var series= [{ type: 'pie', name: 'Group share', data: [ { … -
How to export local CSV file into a Data Table in local webpage through Django
I am fairly new to Django and I need some of your help! I have researched countless of websites and I have no idea how to proceed with what I want to do. Essentially, I have succeeded in reading a local CSV file through the Django model but I have no idea how to display this data into a Data Table on my web page. Im assuming I need a new HTML file in my template folder in order to achieve what I want to do. I know you can some how open the csv file and then create an html file with it but I dont know where to put it in terms of my Django Project...do i put it in views.py, models.py, or a new html file in my template? Any help would be appreciated. Thank you so much! -
django __unicode__() doesn't return a string
Am trying to create a web app with django Am still a beginer at early stages and am having a problem dealing with unicode() here is what I did: from django.db import models # Create your models here. class profile(models.Model): name = models.CharField(max_length=100) description = models.TextField(default="description default Text") location = models.CharField(max_length=120, default="my location default") job = models.CharField(max_length=120, null=True) def __unicode__(self): return self.name unicode is supposed to retun me the name of profile but I get profile object in it place, by the way am using Django 1.10 and python 3.6. this image shows where name is supposed to be -
Reuse cached QuerySet to prevent querying the database
I am trying to reduce the number of database hits in a portion of my app as much as possible as they have quite a negative performance impact. I do all sorts of filtering on a given player's set of matches using any QuerySet operation like filter, exclude, Q objects, etc... player.game_set.filter(Q1) player.game_set.filter(Q2) player.game_set.exclude(Q3) And everytime any of QuerySets sets are being executed, the databse is being hit. I wonder if I could do the following: just hit the database once, to get the superset of the player's games: player.game_set.all() And then filter that cached QuerySet, but still using QuerySet operations like filter, exclude and Q objects. These would act on the cached player.game_set.all() rather than hitting the base every time. Can this be done? -
Connect users to a Django website with React-Native
I have a Django website running, where users can login, save data, take notes, etc. I want to make a mobile app for this website and I am looking into react-native, as I made my website front end with React-JS. I want to be able to fetch users data on the website from the app. I saw that React-Native had the fetch function, similar to AJAX calls. The problem is that I need the user to be authenticated for the POST call to return something, as I am reading the request.user value to grab the proper data. I also know that without the proper csrf token, Django won't allow a POST call. How can I do a fetch with the proper request.user value and pass the csrf security test from the react-native app? -
Declaratively set permissions on Postgres table via Django Model?
We have two different groups working on the same Django database: The web team A team of data scientists We'd like to make it easy for the data scientists to read/write to a subset of a tables using Django models but without giving them write/delete access to the rest of the tables. Our current thought is that we'd like to lock down the tables in the data layer (Postgres) with GRANT and REVOKE style SQL statements, but we'd like to manage those permissions in the models. We'd have two ROLES: data_scientists_rw web_team_admin Instead of manually writing GRANT and REVOKE permissions in each migration, we'd like to have a decorator or a Meta class variable on a model so that when we makemigrations, it will automatically generate the correct SQL. # data_scientists/models.py (pseudocode) class DataScientistModel(models.Model): ... my_special_number = models.FloatField() ... class Meta: data_science_team_editable = True Make the migration: $ ./manage.py makemigrations Auto-generated model (pseudocode): # migrations/0008_new_data_scientist_model.py ... if data_science_team_editable: RunSQL('GRANT INSERT, UPDATE, DELETE ON {tablename} TO data_scientists_rw;') ... Questions: Does this approach seem sensible? How I do hook into makemigrations so that I can auto-generate the RunSQL code? -
Mysqlclient fails to install
I am trying to install mysqlclient on mac to use mysql in a django project. I have made sure that setup tools is installed and that mysql connector c is installed as well. I keep getting the error Command "python setup.py egg_info" failed with error code 1 in. This is my first django project since switching from rails. Is there something I am missing? I am using python 3 and I use pip install mysqlclient. -
DoesNotExist: Contract matching query does not exist
Here is the my problematic code and the traceback related from this code : @staff_member_required @require_http_methods(['POST']) def fax_contract(request, pk=None): if request.is_ajax() and pk: print("Sending contract for request {}".format(pk)) # try: contract = Contract.objects.get(pk=pk) # except Contract.DoesNotExist: # return HttpResponseNotFound(_('Contract not found')) now = datetime.datetime.now() last_faxed = contract.request.last_faxed_at if last_faxed and (now - last_faxed) < settings.LOANWOLF_FAX_GRACE_TIME: return JsonResponse({ 'error': True, 'reload': False, 'message': _('Please wait at least %(minutes)d minutes to resend the contracts') % { 'minutes': settings.LOANWOLF_FAX_GRACE_TIME}, }) else: contract.request.last_faxed_at = datetime.datetime.now() contract.request.save() subject, msg = ('', '') # TODO: audit log try: send_mail = send_mail(subject, msg, settings.LOANWOLF_FAX_EMAIL_FROM, settings.LOANWOLF_FAX_EMAIL_TO.format(contract.request.customerprofile.fax), fail_silently=False) return JsonResponse({'success': True, 'reload': True}) except Exception as e: return JsonResponse({'error': True, 'message': str(e)}) and Traceback (most recent call last): File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = response_for_exception(request, exc) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 86, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response … -
Create Django Super User in Elastic Beanstalk Postgresql
I am trying to create a superuser for my app in Django. It's easy in localhost. However, I can't figure out how to do it in Elastic Beanstalk. The methods I've tried are aws guide and realpython . However, none seems to work. My database is posgresql and it's connected to my application. However no superuser is being created through migrations. How is it supposed to work? -
Django Postgres Full Text TrigramSimilarity Multiple Fields
I am trying to figure out how to use TrigramSimilarity with unaccent for multiple fields. So far i have: def filter_by_location(self, queryset, location): log.info('Filtering location: "{location}"'.format(**locals())) queryset = queryset.filter( Q(accommodation__district__name__unaccent__trigram_similar=location) | Q(accommodation__municipality__name__unaccent__trigram_similar=location) | Q(accommodation__settlement__name__unaccent__trigram_similar=location) ) But i read in the documentation that i could order by similarity (not sure if the code above does that automatically), so i tried doing: queryset = queryset.filter( Q(accommodation__district__name__unaccent__trigram_similar=location) | Q(accommodation__municipality__name__unaccent__trigram_similar=location) | Q(accommodation__settlement__name__unaccent__trigram_similar=location) ).annotate( similarity=TrigramSimilarity( 'accommodation__district__name', location ) + TrigramSimilarity( 'accommodation__municipality__name', location ) + TrigramSimilarity( 'accommodation__settlement__name', location ), ).filter(similarity__gt=0.3).order_by('-similarity') I soon realized that the + in TrigramSimilarity was not doing the OR, but i need to full text search across all those different fields. What is the correct syntax for me to achieve that (use an OR instead of and AND) taking query performance into account?? Thanks -
Error: Error: No NgModule metadata found for 'AppComponent'
I am trying to use Django with Angular2. I have a working Django project. I am getting this error while trying to use Angular2 with it: Error: Error: No NgModule metadata found for 'AppComponent'. at new BaseException (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:5116:27) at NgModuleResolver.resolve (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:12956:27) at CompileMetadataResolver.getNgModuleMetadata (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:13200:51) at RuntimeCompiler._compileComponents (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:15845:51) at RuntimeCompiler._compileModuleAndComponents (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:15769:41) at RuntimeCompiler.compileModuleAsync (http://user:8000/ng/node_modules/@angular/compiler//bundles/compiler.umd.js:15746:25) at PlatformRef_._bootstrapModuleWithZone (http://user:8000/ng/node_modules/@angular/core//bundles/core.umd.js:9991:29) at PlatformRef_.bootstrapModule (http://user:8000/ng/node_modules/@angular/core//bundles/core.umd.js:9984:25) at Object.eval (http://user:8000/ng/src/main.js:5:53) at eval (http://user:8000/ng/src/main.js:17:4) Evaluating http://user:8000/ng/src/main.js Error loading http://user:8000/ng/src/main.js Part of package.json file: "dependencies": { "@angular/common": "2.0.0-rc.5", "@angular/compiler": "2.0.0-rc.5", "@angular/core": "2.0.0-rc.5", "@angular/forms": "0.2.0", "@angular/http": "2.0.0-rc.5", "@angular/platform-browser": "2.0.0-rc.5", "@angular/platform-browser-dynamic": "2.0.0-rc.5", "@angular/router": "3.0.0-beta.2", "@angular/router-deprecated": "2.0.0-rc.2", "@angular/upgrade": "2.0.0-rc.5", "systemjs": "0.19.27", "core-js": "^2.4.0", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.6", "zone.js": "^0.6.12", "angular2-in-memory-web-api": "0.0.15", "bootstrap": "^3.3.6"}, main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { AppComponent } from './app/app.component'; import {appRouterProviders} from "./app/app.route"; import {HTTP_PROVIDERS} from "@angular/http"; import {enableProdMode} from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; platformBrowserDynamic().bootstrapModule(AppModule); app.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule,FormsModule,HttpModule, RouterModule.forRoot( ROUTES, { useHash: true } ) ], declarations: [ AppComponent … -
What's an appropriate way to implement a REST sms verification system in django?
I am currently working on a SMS verification system. My design: Request For Verification Code [GET /verify/SOME_PHONE_NUMBER] Verify code [POST /verify/SOME_PHONE_NUMBER] { "verification_code": "1234" } Here is my code def verify(request, phone_number): if request.method == 'GET': try: record = VerificationRecord.objects.get(phone_number=phone_number) if record.is_too_recent(): return HttpResponse('Too Often', status=403) record.generated_time = datetime.now(tz=UTC) record.verification_code = generate_code() record.save() except VerificationRecord.DoesNotExist: VerificationRecord.objects.create(phone_number=phone_number, verification_code=generate_code()) send_verification_code(phone_number) return HttpResponse(status=202) elif request.method == 'POST': verification_code = request.POST['verification_code'] record = get_object_or_404(VerificationRecord, phone_number=phone_number) if record.is_expired() or record.reach_limit() or record.verification_code != verification_code: record.fail_count += 1 record.save() return HttpResponse('Invalid Verification', status=401) else: record.fail_count = 10 record.save() do_success(request, phone_number) return HttpResponse() Is there any better way to implement this? I feel my code is redundant. -
django-cms restrict page view based on user credentials
I am using django-cms as an app in my website, to provide CMS/blog type functionality. Furthermore, I am using a custom user model in django, and I want to use logic based on the custom user model to determine whether to allow a user to be able to view a page (or not). Assuming that my custom User model looks like this: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=False, blank=False) def is_old_enough(self): # logic here ... return age > 16 Assume I have created Page1, Page2 and Page3 in django-cms; further assume that Page3 contains material that is not suitable for anyone below the age of 16. A rather contrived example of what I want to do, follows below: I want to be able to impose a restriction on viewing of Page3 as follows: User is authenticated (logged in) User belongs to Group 'XXX' User is old enough With django, this functional requirement can be implemented by using decorators in the view - however, I can't find any way of implementing such functionality, when using pages coming from django-cms. How do I … -
When should we use advanced parameters of save()?
Normally we save an instance to the database simply with inst.save(), but Django uses user.save(using=self._db) in its source code. Also, it uses user.save(update_fields=['last_login']) elsewhere. This somewhat confuses me. To make things worse, the document for the save() method is extremely simple: Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)[source] If you want customized saving behavior, you can override this save() method. See Overriding predefined model methods for more details. The model save process also has some subtleties; see the sections below. It doesn't even contain the explanation of those parameters! My question is: when should we use the advanced parameters of save()? For example, if we change user.save(using=self._db) to user.save(), would something bad happen? I've done a couple of experiments myself, and nothing went wrong, but I think all these parameters must be passed for some reasons. -
MongoDB lost in droplet Digital Ocean
I've built a Django web app on a droplet of Digital Ocean. The app was working fine. Today, when I opened my web app, no data appeared. I had a look at the droplet (server), and I found that all data in my mongodb is lost. Especially, when I type show dbs in mongodb shell, it said: DB_HAS_BEEN_DROPPED 0.000GB Then I rebooted the server, and it worked again. The collections come back but only old data is available. New data, that I've been collected in recent days, is lost. I faced a similar problem before. For that time, my process running mongodb was even turned off. I suspected that my droplet is hacked by someone. Is that correct or that's the problem of mongodb? I also curious about security policy of Digital Ocean because when I set up a server one month ago, they sent me a message telling me that the server had strange outgoing traffic, and they locked my server just one day after setting up. Thanks. -
How to rollback database in case of an IntegrityError in Django?
The following static method (taken from flasky) is a way to populate the database with fake data, and I want to import it to Django. models.py class User(UserMixin, db.Model): # ...... @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() The problem is, while I can do something like User.objects.create(...), I don't know how to rollback the database in case an IntegrityError happens (presumable due to a duplicate primary key). -
Django API with different levels
Currently, the project I'm working on has an API like the following: api/ visitors/ # Endpoint returning list of visitors visitor-rates/ # Endpoint returning visitors per time gift-shop-orders/ # Endpoint returning purchases at the gift shop order-rates/ # Endpoint returning purchases per time What I'd like to do is group the visitor and gift shop endpoints under their own sub-heading. For example: api/ visits/ visitors/ rates/ gift-shop/ orders/ rates/ Note that visits and gift-shop only have the job of listing out the URLs that are available under the respective subheading. So, a GET request to /api/visits should return: { "visitors": "/api/visits/visitors", "rates": "/api/visits/rates" } In other words, I'd like /api/visits/ and /api/gift-shop/ to have the same behavior as the default router view used by Django for displaying the endpoints available in the root of the API (/api/). I've tried simply nesting just the URLs together. So, suppose I've defined routers for the visitor endpoints and shop endpoints. I've tried: api_patterns = [ url(r'^visits/', include(visitor_router.urls)), url(r'^gift-shop/', include(shop_router.urls)), ] urlpatterns = [ url(r'^api/', include(api_patterns)), ] This makes it so that requests to /api/visits/ and /api/gift-shop/ respond correctly. However, if I go to /api/, no links to /api/visits or /api/gift-shop are given. This …